2 Commits

Author SHA1 Message Date
73af6d2031 лабораторная 3 2024-04-03 16:43:38 +04:00
985dd19b2c коллекции и компания 2024-03-23 11:55:48 +04:00
13 changed files with 1205 additions and 87 deletions

View File

@@ -0,0 +1,119 @@
///using ProjectByldozer.CollectionGenericObjects;
using ProjectByldozer.Drawnings;
namespace ProjectByldozer.CollectionGenericObjects;
/// <summary>
/// Абстракция компании, хранящий коллекцию автомобилей
/// </summary>
public abstract class AbstractCompany
{
/// <summary>
/// Размер места (ширина)
/// </summary>
protected readonly int _placeSizeWidth = 210;
/// <summary>
/// Размер места (высота)
/// </summary>
protected readonly int _placeSizeHeight = 83;
/// <summary>
/// Ширина окна
/// </summary>
protected readonly int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
protected readonly int _pictureHeight;
/// <summary>
/// Коллекция бульдозеров
/// </summary>
protected ICollectionGenericObjects<DrawningTrackedCar>? _collection = null;
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth">Ширина окна</param>
/// <param name="picHeight">Высота окна</param>
/// <param name="collection">Коллекция автомобилей</param>
public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects<DrawningTrackedCar> collection)
{
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.SetMaxCount = GetMaxCount;
}
/// <summary>
/// Перегрузка оператора сложения для класса
/// </summary>
/// <param name="company">Компания</param>
/// <param name="car">Добавляемый объект</param>
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningTrackedCar TrackedCar)
{
return company._collection.Insert(TrackedCar);
}
/// <summary>
/// Перегрузка оператора удаления для класса
/// </summary>
/// <param name="company">Компания</param>
/// <param name="position">Номер удаляемого объекта</param>
/// <returns></returns>
public static DrawningTrackedCar operator -(AbstractCompany company, int position)
{
return company._collection?.Remove(position);
}
/// <summary>
/// Получение случайного объекта из коллекции
/// </summary>
/// <returns></returns>
public DrawningTrackedCar? 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)
{
DrawningTrackedCar? 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,19 @@

namespace ProjectByldozer.CollectionGenericObjects;
public enum CollectionType
{
/// <summary>
/// Неопределено
/// </summary>
None = 0,
/// <summary>
/// Массив
/// </summary>
Massive = 1,
/// <summary>
/// Список
/// </summary>
List = 2
}

View File

@@ -0,0 +1,47 @@
namespace ProjectByldozer.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,74 @@

namespace ProjectByldozer.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
public class ListGenericObjects<T>: ICollectionGenericObjects<T>
where T : class
{
/// <summary>
/// Список объектов, которые храним
/// </summary>
private readonly List<T?> _collection;
/// <summary>
/// Максимально допустимое число объектов в списке
/// </summary>
private int _maxCount;
public int Count => _collection.Count;
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } }
/// <summary>
/// Конструктор
/// </summary>
public ListGenericObjects()
{
_collection = new();
}
public T? Get(int position)
{
// TODO проверка позиции
if (position >= Count || position < 0) return null;
return _collection[position];
}
public int Insert(T obj)
{
// TODO проверка, что не превышено максимальное количество элементов
// TODO вставка в конец набора
if (Count == _maxCount) return -1;
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position)
{
// TODO проверка, что не превышено максимальное количество элементов
// TODO проверка позиции
// TODO вставка по позиции
if (Count == _maxCount) return -1;
if (position >= Count || position < 0) return -1;
_collection.Insert(position, obj);
return position;
}
public T Remove(int position)
{
// TODO проверка позиции
// TODO удаление объекта из списка
if (position >= Count || position < 0) return null;
T obj = _collection[position];
_collection.RemoveAt(position);
return obj;
}
}

View File

@@ -0,0 +1,114 @@
namespace ProjectByldozer.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)
{
// TODO проверка позиции
if (position >= _collection.Length || position < 0)
{ return null; }
return _collection[position];
}
public int Insert(T obj)
{
// TODO вставка в свободное место набора
int index = 0;
while (index < _collection.Length)
{
if (_collection[index] == null)
{
_collection[index] = obj;
return index;
}
index++;
}
return -1;
}
public int Insert(T obj, int position)
{
// TODO проверка позиции
// TODO проверка, что элемент массива по этой позиции пустой, если нет, то
// ищется свободное место после этой позиции и идет вставка туда
// если нет после, ищем до
// TODO вставка
if (position >= _collection.Length || position < 0)
{ return -1; }
if (_collection[position] == null)
{
_collection[position] = obj;
return position;
}
int index;
for (index = position + 1; index < _collection.Length; ++index)
{
if (_collection[index] == null)
{
_collection[position] = obj;
return position;
}
}
for (index = position - 1; index >= 0; --index)
{
if (_collection[index] == null)
{
_collection[position] = obj;
return position;
}
}
return -1;
}
public T Remove(int position)
{
// TODO проверка позиции
// TODO удаление объекта из массива, присвоив элементу массива значение null
if (position >= _collection.Length || position < 0)
{ return null; }
T obj = _collection[position];
_collection[position] = null;
return obj;
}
}

View File

@@ -0,0 +1,74 @@

namespace ProjectByldozer.CollectionGenericObjects;
// Класс-хранилище коллекций
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : class
{
/// <summary>
/// Словарь (хранилище) с коллекциями
/// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
/// <summary>
/// Возвращение списка названий коллекций
/// </summary>
public List<string> Keys => _storages.Keys.ToList();
/// <summary>
/// Конструктор
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
}
/// <summary>
/// Добавление коллекции в хранилище
/// </summary>
/// <param name="name">Название коллекции</param>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
{
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом
// TODO Прописать логику для добавления
if (_storages.ContainsKey(name)) return;
if (collectionType == CollectionType.None) return;
else if (collectionType == CollectionType.Massive)
_storages[name] = new MassiveGenericObjects<T>();
else if (collectionType == CollectionType.List)
_storages[name] = new ListGenericObjects<T>();
}
/// <summary>
/// Удаление коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
{
// TODO Прописать логику для удаления коллекции
if (_storages.ContainsKey(name))
_storages.Remove(name);
}
/// <summary>
/// Доступ к коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
/// <returns></returns>
public ICollectionGenericObjects<T>? this[string name]
{
get
{
// TODO Продумать логику получения объекта
if (_storages.ContainsKey(name))
return _storages[name];
return null;
}
}
}

View File

@@ -0,0 +1,66 @@

using ProjectByldozer.Drawnings;
namespace ProjectByldozer.CollectionGenericObjects;
public class TrackedCarGarage : AbstractCompany
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
/// <param name="collection"></param>
public TrackedCarGarage(int picWidth, int picHeight, ICollectionGenericObjects<DrawningTrackedCar> collection) : base(picWidth, picHeight, collection)
{
}
protected override void DrawBackgound(Graphics g)
{
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
Pen pen = new(Color.Black, 3);
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height + 1; ++j)
{
g.DrawLine(pen, i * _placeSizeWidth, j * _placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth - 15, j * _placeSizeHeight);
}
}
}
protected override void SetObjectsPosition()
{
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
int curWidth = width - 1;
int curHeight = 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 * curWidth + 20, curHeight * _placeSizeHeight + 2);
}
if (curWidth > 0)
curWidth--;
else
{
curWidth = width - 1;
curHeight--;
}
if (curHeight < 0)
{
return;
}
}
}
}

View File

@@ -29,12 +29,10 @@
private void InitializeComponent() private void InitializeComponent()
{ {
pictureBoxByldozer = new PictureBox(); pictureBoxByldozer = new PictureBox();
buttonCreateByldozer = new Button();
buttonLeft = new Button(); buttonLeft = new Button();
buttonUp = new Button(); buttonUp = new Button();
buttonDown = new Button(); buttonDown = new Button();
buttonRight = new Button(); buttonRight = new Button();
buttonCreatecar = new Button();
comboBoxStrategy = new ComboBox(); comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button(); buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxByldozer).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxByldozer).BeginInit();
@@ -45,29 +43,16 @@
pictureBoxByldozer.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; pictureBoxByldozer.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
pictureBoxByldozer.Location = new Point(-2, -1); pictureBoxByldozer.Location = new Point(-2, -1);
pictureBoxByldozer.Name = "pictureBoxByldozer"; pictureBoxByldozer.Name = "pictureBoxByldozer";
pictureBoxByldozer.Size = new Size(751, 406); pictureBoxByldozer.Size = new Size(976, 497);
pictureBoxByldozer.TabIndex = 0; pictureBoxByldozer.TabIndex = 0;
pictureBoxByldozer.TabStop = false; pictureBoxByldozer.TabStop = false;
pictureBoxByldozer.Click += pictureBoxByldozer_Click;
//
// buttonCreateByldozer
//
buttonCreateByldozer.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateByldozer.Location = new Point(26, 367);
buttonCreateByldozer.Name = "buttonCreateByldozer";
buttonCreateByldozer.Size = new Size(120, 26);
buttonCreateByldozer.TabIndex = 1;
buttonCreateByldozer.Text = "Создать бульдозер";
buttonCreateByldozer.TextAlign = ContentAlignment.TopRight;
buttonCreateByldozer.UseVisualStyleBackColor = true;
buttonCreateByldozer.Click += ButtonCreateByldozer_Click;
// //
// buttonLeft // buttonLeft
// //
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = Properties.Resources.arrowLeft; buttonLeft.BackgroundImage = Properties.Resources.arrowLeft;
buttonLeft.BackgroundImageLayout = ImageLayout.Stretch; buttonLeft.BackgroundImageLayout = ImageLayout.Stretch;
buttonLeft.Location = new Point(620, 370); buttonLeft.Location = new Point(845, 461);
buttonLeft.Name = "buttonLeft"; buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(35, 35); buttonLeft.Size = new Size(35, 35);
buttonLeft.TabIndex = 2; buttonLeft.TabIndex = 2;
@@ -79,7 +64,7 @@
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = Properties.Resources.arrowUp; buttonUp.BackgroundImage = Properties.Resources.arrowUp;
buttonUp.BackgroundImageLayout = ImageLayout.Stretch; buttonUp.BackgroundImageLayout = ImageLayout.Stretch;
buttonUp.Location = new Point(661, 329); buttonUp.Location = new Point(886, 420);
buttonUp.Name = "buttonUp"; buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(35, 35); buttonUp.Size = new Size(35, 35);
buttonUp.TabIndex = 3; buttonUp.TabIndex = 3;
@@ -91,7 +76,7 @@
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = Properties.Resources.arrowDown; buttonDown.BackgroundImage = Properties.Resources.arrowDown;
buttonDown.BackgroundImageLayout = ImageLayout.Stretch; buttonDown.BackgroundImageLayout = ImageLayout.Stretch;
buttonDown.Location = new Point(661, 370); buttonDown.Location = new Point(886, 461);
buttonDown.Name = "buttonDown"; buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(35, 35); buttonDown.Size = new Size(35, 35);
buttonDown.TabIndex = 4; buttonDown.TabIndex = 4;
@@ -103,38 +88,26 @@
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = Properties.Resources.arrowRight; buttonRight.BackgroundImage = Properties.Resources.arrowRight;
buttonRight.BackgroundImageLayout = ImageLayout.Stretch; buttonRight.BackgroundImageLayout = ImageLayout.Stretch;
buttonRight.Location = new Point(702, 370); buttonRight.Location = new Point(927, 461);
buttonRight.Name = "buttonRight"; buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(35, 35); buttonRight.Size = new Size(35, 35);
buttonRight.TabIndex = 5; buttonRight.TabIndex = 5;
buttonRight.UseVisualStyleBackColor = true; buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click; buttonRight.Click += ButtonMove_Click;
// //
// buttonCreatecar
//
buttonCreatecar.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreatecar.Location = new Point(164, 367);
buttonCreatecar.Name = "buttonCreatecar";
buttonCreatecar.Size = new Size(179, 26);
buttonCreatecar.TabIndex = 6;
buttonCreatecar.Text = "Создать гусеничную машину";
buttonCreatecar.TextAlign = ContentAlignment.TopRight;
buttonCreatecar.UseVisualStyleBackColor = true;
buttonCreatecar.Click += ButtonCreatecar_Click;
//
// comboBoxStrategy // comboBoxStrategy
// //
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(616, 12); comboBoxStrategy.Location = new Point(828, 12);
comboBoxStrategy.Name = "comboBoxStrategy"; comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(121, 23); comboBoxStrategy.Size = new Size(138, 23);
comboBoxStrategy.TabIndex = 7; comboBoxStrategy.TabIndex = 7;
// //
// buttonStrategyStep // buttonStrategyStep
// //
buttonStrategyStep.Location = new Point(662, 41); buttonStrategyStep.Location = new Point(891, 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;
@@ -146,15 +119,13 @@
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(749, 405); ClientSize = new Size(974, 496);
Controls.Add(buttonStrategyStep); Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy); Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreatecar);
Controls.Add(buttonRight); Controls.Add(buttonRight);
Controls.Add(buttonDown); Controls.Add(buttonDown);
Controls.Add(buttonUp); Controls.Add(buttonUp);
Controls.Add(buttonLeft); Controls.Add(buttonLeft);
Controls.Add(buttonCreateByldozer);
Controls.Add(pictureBoxByldozer); Controls.Add(pictureBoxByldozer);
Name = "FormByldozer"; Name = "FormByldozer";
Text = "Бульдозер"; Text = "Бульдозер";
@@ -165,12 +136,10 @@
#endregion #endregion
private PictureBox pictureBoxByldozer; private PictureBox pictureBoxByldozer;
private Button buttonCreateByldozer;
private Button buttonLeft; private Button buttonLeft;
private Button buttonUp; private Button buttonUp;
private Button buttonDown; private Button buttonDown;
private Button buttonRight; private Button buttonRight;
private Button buttonCreatecar;
private ComboBox comboBoxStrategy; private ComboBox comboBoxStrategy;
private Button buttonStrategyStep; private Button buttonStrategyStep;
} }

View File

@@ -17,6 +17,17 @@ public partial class FormByldozer : Form
/// стратегия перемещения /// стратегия перемещения
/// </summary> /// </summary>
private AbstractStrategy? _strategy; private AbstractStrategy? _strategy;
public DrawningTrackedCar SetTrackedCar
{
set
{
_drawningTrackedCar = value;
_drawningTrackedCar.SetPictureSize(pictureBoxByldozer.Width, pictureBoxByldozer.Height);
comboBoxStrategy.Enabled = true;
_strategy = null;
Draw();
}
}
/// <summary> /// <summary>
/// инциализация формы /// инциализация формы
/// </summary> /// </summary>
@@ -42,49 +53,6 @@ public partial class FormByldozer : Form
} }
/// <summary>
/// Создание объекта класса-перемещения
/// </summary>
/// <param name="type">Тип создаваемого объекта</param>
private void CreateObject(string type)
{
Random random = new();
switch (type)
{
case nameof(DrawningTrackedCar):
_drawningTrackedCar = new DrawningTrackedCar(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(DrawningByldozer):
_drawningTrackedCar = new DrawningByldozer(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)), Convert.ToBoolean(random.Next(0, 2)));
break;
default:
return;
}
_drawningTrackedCar.SetPictureSize(pictureBoxByldozer.Width, pictureBoxByldozer.Height);
_drawningTrackedCar.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 ButtonCreateByldozer_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningByldozer));
/// <summary>
/// обработка нажатия кнопки "создать машину"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreatecar_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningTrackedCar));
/// <summary> /// <summary>
/// премещение объекта по форме /// премещение объекта по форме
/// </summary> /// </summary>
@@ -158,9 +126,6 @@ public partial class FormByldozer : Form
} }
} }
private void pictureBoxByldozer_Click(object sender, EventArgs e)
{
}
} }

View File

@@ -0,0 +1,301 @@
namespace ProjectByldozer
{
partial class FormCarCollection
{
/// <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();
buttonCreateCompany = new Button();
panelStorage = new Panel();
buttonCollectionDel = new Button();
listBoxCollection = new ListBox();
buttonCjllecyionAdd = new Button();
radioButtonList = new RadioButton();
radioButtonMassiv = new RadioButton();
textBoxCollectionName = new TextBox();
labelCollectionName = new Label();
buttonRefresh = new Button();
buttonGoToCheck = new Button();
buttonDelCar = new Button();
maskedTextBox = new MaskedTextBox();
buttonAddByldozer = new Button();
buttonAddTrackedCar = new Button();
comboBoxSelectionCompany = new ComboBox();
pictureBox = new PictureBox();
panelCompanyTools = new Panel();
groupBoxTools.SuspendLayout();
panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
panelCompanyTools.SuspendLayout();
SuspendLayout();
//
// groupBoxTools
//
groupBoxTools.Controls.Add(comboBoxSelectionCompany);
groupBoxTools.Controls.Add(buttonCreateCompany);
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(778, 0);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(209, 501);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// buttonCreateCompany
//
buttonCreateCompany.Location = new Point(3, 267);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(203, 20);
buttonCreateCompany.TabIndex = 8;
buttonCreateCompany.Text = "Создать компанию";
buttonCreateCompany.UseVisualStyleBackColor = true;
buttonCreateCompany.Click += ButtonCreateCompany_Click;
//
// panelStorage
//
panelStorage.Controls.Add(buttonCollectionDel);
panelStorage.Controls.Add(listBoxCollection);
panelStorage.Controls.Add(buttonCjllecyionAdd);
panelStorage.Controls.Add(radioButtonList);
panelStorage.Controls.Add(radioButtonMassiv);
panelStorage.Controls.Add(textBoxCollectionName);
panelStorage.Controls.Add(labelCollectionName);
panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 19);
panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(203, 214);
panelStorage.TabIndex = 7;
//
// buttonCollectionDel
//
buttonCollectionDel.Location = new Point(3, 182);
buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionDel.Size = new Size(191, 20);
buttonCollectionDel.TabIndex = 6;
buttonCollectionDel.Text = "Удалить коллекцию";
buttonCollectionDel.UseVisualStyleBackColor = true;
buttonCollectionDel.Click += ButtonCollectionDel_Click;
//
// listBoxCollection
//
listBoxCollection.FormattingEnabled = true;
listBoxCollection.ItemHeight = 15;
listBoxCollection.Location = new Point(3, 112);
listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(191, 64);
listBoxCollection.TabIndex = 5;
//
// buttonCjllecyionAdd
//
buttonCjllecyionAdd.Location = new Point(3, 86);
buttonCjllecyionAdd.Name = "buttonCjllecyionAdd";
buttonCjllecyionAdd.Size = new Size(191, 20);
buttonCjllecyionAdd.TabIndex = 4;
buttonCjllecyionAdd.Text = "Добавить коллекцию";
buttonCjllecyionAdd.UseVisualStyleBackColor = true;
buttonCjllecyionAdd.Click += ButtonCjllecyionAdd_Click;
//
// radioButtonList
//
radioButtonList.AutoSize = true;
radioButtonList.Location = new Point(110, 61);
radioButtonList.Name = "radioButtonList";
radioButtonList.Size = new Size(66, 19);
radioButtonList.TabIndex = 3;
radioButtonList.TabStop = true;
radioButtonList.Text = "Список";
radioButtonList.UseVisualStyleBackColor = true;
//
// radioButtonMassiv
//
radioButtonMassiv.AutoSize = true;
radioButtonMassiv.Location = new Point(16, 61);
radioButtonMassiv.Name = "radioButtonMassiv";
radioButtonMassiv.Size = new Size(67, 19);
radioButtonMassiv.TabIndex = 2;
radioButtonMassiv.TabStop = true;
radioButtonMassiv.Text = "Массив";
radioButtonMassiv.UseVisualStyleBackColor = true;
//
// textBoxCollectionName
//
textBoxCollectionName.Location = new Point(3, 28);
textBoxCollectionName.Name = "textBoxCollectionName";
textBoxCollectionName.Size = new Size(191, 23);
textBoxCollectionName.TabIndex = 1;
//
// labelCollectionName
//
labelCollectionName.AutoSize = true;
labelCollectionName.Location = new Point(38, 10);
labelCollectionName.Name = "labelCollectionName";
labelCollectionName.Size = new Size(122, 15);
labelCollectionName.TabIndex = 0;
labelCollectionName.Text = "Название коллекции";
//
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(3, 181);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(208, 25);
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(3, 149);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(205, 26);
buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
buttonGoToCheck.Click += ButtonGoToCheck_Click;
//
// buttonDelCar
//
buttonDelCar.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonDelCar.Location = new Point(3, 120);
buttonDelCar.Name = "buttonDelCar";
buttonDelCar.Size = new Size(205, 23);
buttonDelCar.TabIndex = 4;
buttonDelCar.Text = "Удаление машины";
buttonDelCar.UseVisualStyleBackColor = true;
buttonDelCar.Click += ButtonDelCar_Click;
//
// maskedTextBox
//
maskedTextBox.Location = new Point(3, 91);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(205, 23);
maskedTextBox.TabIndex = 3;
maskedTextBox.ValidatingType = typeof(int);
//
// buttonAddByldozer
//
buttonAddByldozer.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddByldozer.Location = new Point(3, 54);
buttonAddByldozer.Name = "buttonAddByldozer";
buttonAddByldozer.Size = new Size(205, 31);
buttonAddByldozer.TabIndex = 2;
buttonAddByldozer.Text = "Добавления бульдозера";
buttonAddByldozer.UseVisualStyleBackColor = true;
buttonAddByldozer.Click += ButtonAddByldozer_Click;
//
// buttonAddTrackedCar
//
buttonAddTrackedCar.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddTrackedCar.Location = new Point(3, 17);
buttonAddTrackedCar.Name = "buttonAddTrackedCar";
buttonAddTrackedCar.Size = new Size(205, 31);
buttonAddTrackedCar.TabIndex = 1;
buttonAddTrackedCar.Text = "Добавления гусеничной машины";
buttonAddTrackedCar.UseVisualStyleBackColor = true;
buttonAddTrackedCar.Click += ButtonAddTrackedCar_Click;
//
// comboBoxSelectionCompany
//
comboBoxSelectionCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
comboBoxSelectionCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectionCompany.FormattingEnabled = true;
comboBoxSelectionCompany.Items.AddRange(new object[] { "Хранилище" });
comboBoxSelectionCompany.Location = new Point(3, 238);
comboBoxSelectionCompany.Name = "comboBoxSelectionCompany";
comboBoxSelectionCompany.Size = new Size(203, 23);
comboBoxSelectionCompany.TabIndex = 0;
comboBoxSelectionCompany.SelectedIndexChanged += ComboBoxSelectionCompany_SelectedIndexChanged;
//
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(778, 501);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonAddTrackedCar);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(buttonAddByldozer);
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Controls.Add(maskedTextBox);
panelCompanyTools.Controls.Add(buttonDelCar);
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(776, 293);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(208, 208);
panelCompanyTools.TabIndex = 9;
//
// FormCarCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(987, 501);
Controls.Add(panelCompanyTools);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Name = "FormCarCollection";
Text = "коллекция бульдозеров";
groupBoxTools.ResumeLayout(false);
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
panelCompanyTools.ResumeLayout(false);
panelCompanyTools.PerformLayout();
ResumeLayout(false);
}
#endregion
private GroupBox groupBoxTools;
private ComboBox comboBoxSelectionCompany;
private Button buttonAddByldozer;
private Button buttonAddTrackedCar;
private MaskedTextBox maskedTextBox;
private PictureBox pictureBox;
private Button buttonDelCar;
private Button buttonRefresh;
private Button buttonGoToCheck;
private Panel panelStorage;
private Label labelCollectionName;
private TextBox textBoxCollectionName;
private RadioButton radioButtonList;
private RadioButton radioButtonMassiv;
private Button buttonCjllecyionAdd;
private ListBox listBoxCollection;
private Button buttonCreateCompany;
private Button buttonCollectionDel;
private Panel panelCompanyTools;
}
}

View File

@@ -0,0 +1,249 @@
using ProjectByldozer.CollectionGenericObjects;
using ProjectByldozer.Drawnings;
namespace ProjectByldozer;
/// <summary>
/// Форма работы с компанией и ее коллекцией
/// </summary>
public partial class FormCarCollection : Form
{
/// <summary>
/// Хранилище коллекций
/// </summary>
private readonly StorageCollection<DrawningTrackedCar> _storageCollection;
/// <summary>
/// Компания
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Конструктор
/// </summary>
public FormCarCollection()
{
InitializeComponent();
_storageCollection = new();
}
private void ComboBoxSelectionCompany_SelectedIndexChanged(object sender, EventArgs e)
{
panelCompanyTools.Enabled = false;
}
/// <summary>
/// Добавление обычной машины
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddByldozer_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningByldozer));
/// /// Добавление полного экскаватора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddTrackedCar_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningTrackedCar));
private void CreateObject(string type)
{
if (_company == null)
{
return;
}
Random random = new();
DrawningTrackedCar drawningTrackedCar;
switch (type)
{
case nameof(DrawningTrackedCar):
drawningTrackedCar = new DrawningTrackedCar(random.Next(100, 300), random.Next(1000, 3000), GetColor(random));
break;
case nameof(DrawningByldozer):
// TODO вызов диалогового окна для выбора цвета
drawningTrackedCar = new DrawningByldozer(random.Next(100, 300), random.Next(1000, 3000),
GetColor(random), GetColor(random),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
break;
default:
return;
}
if (_company + drawningTrackedCar != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
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;
}
private void ButtonDelCar_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
int pos = Convert.ToInt32(maskedTextBox.Text);
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
private void ButtonGoToCheck_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
DrawningTrackedCar? trackedcar = null;
int counter = 100;
while (trackedcar == null)
{
trackedcar = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
}
if (trackedcar == null)
{
return;
}
FormByldozer form = new()
{
SetTrackedCar = trackedcar
};
form.ShowDialog();
}
private void ButtonRefresh_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
pictureBox.Image = _company.Show();
}
/// <summary>
/// добавление
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCjllecyionAdd_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassiv.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
CollectionType collectionType = CollectionType.None;
if (radioButtonMassiv.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems();
}
private void RerfreshListBoxItems()
{
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
string? colName = _storageCollection.Keys?[i];
if (!string.IsNullOrEmpty(colName))
{
listBoxCollection.Items.Add(colName);
}
}
}
/// <summary>
/// удаление коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCollectionDel_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateCompany_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
ICollectionGenericObjects<DrawningTrackedCar>? collection =
_storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
return;
}
switch (comboBoxSelectionCompany.Text)
{
case "Хранилище":
_company = new TrackedCarGarage(pictureBox.Width, pictureBox.Height, collection);
break;
}
panelCompanyTools.Enabled = true;
RerfreshListBoxItems();
}
}

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

@@ -11,7 +11,8 @@ namespace ProjectByldozer
// 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 FormByldozer());
Application.Run(new FormCarCollection());
} }
} }
} }