lab3 ready

This commit is contained in:
LivelyPuer 2024-03-13 19:49:07 +04:00
parent 6a08c454c5
commit fe90aefffa
14 changed files with 884 additions and 100 deletions

View File

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

View File

@ -0,0 +1,123 @@
using System.Runtime.Remoting;
namespace ProjectElectroTrans.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];
}
return null;
}
public bool Insert(T obj)
{
// вставка в свободное место набора
for (int i = 0; i< Count; i++)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return true;
}
}
return false;
}
public bool Insert(T obj, int position)
{
// проверка позиции
if (position < 0 || position >= Count)
{
return false;
}
// проверка, что элемент массива по этой позиции пустой, если нет, то
// ищется свободное место после этой позиции и идет вставка туда
// если нет после, ищем до
if (_collection[position] != null)
{
bool pushed = false;
for (int index = position + 1; index < Count; index++) {
if (_collection[index] == null)
{
position = index;
pushed = true;
break;
}
}
if (!pushed)
{
for (int index = position- 1; index >= 0; index--)
{
if (_collection[index] == null)
{
position = index;
pushed = true;
break;
}
}
}
if (!pushed)
{
return false;
}
}
// вставка
_collection[position] = obj;
return false;
}
public bool Remove(int position)
{
// проверка позиции
if (position < 0 || position >= Count)
{
return false;
}
// удаление объекта из массива, присвоив элементу массива значение null
_collection[position] = null;
return true;
}
}

View File

@ -0,0 +1,55 @@
using ProjectElectroTrans.Drawnings;
using ProjectElectroTrans.Entities;
using System;
namespace ProjectElectroTrans.CollectionGenericObjects;
/// <summary>
/// Реализация абстрактной компании - аренда поезда
/// </summary>
public class TransDepoService : AbstractCompany
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
/// <param name="collection"></param>
public TransDepoService(int picWidth, int picHeight, ICollectionGenericObjects<DrawingTrans> collection) : base(picWidth, picHeight, collection)
{
}
protected override void DrawBackgound(Graphics g)
{
Pen pen = new(Color.Black);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for(int j = 0; j < _pictureHeight / _placeSizeHeight; j++)
{
g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * j), new((int)(_placeSizeWidth * (i + 0.5f)), _placeSizeHeight * j));
g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * j), new(_placeSizeWidth * i, _placeSizeHeight * (j + 1)));
}
g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * (_pictureHeight / _placeSizeHeight)), new((int)(_placeSizeWidth * (i + 0.5f)), _placeSizeHeight * (_pictureHeight / _placeSizeHeight)));
}
}
protected override void SetObjectsPosition()
{
int n = 0;
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight; j++)
{
DrawingTrans? drawingTrans = _collection?.Get(n);
n++;
if (drawingTrans != null)
{
drawingTrans.SetPictureSize(_pictureWidth, _pictureHeight);
drawingTrans.SetPosition(i * _placeSizeWidth + 5, j * _placeSizeHeight + 5);
}
}
}
}
}

View File

@ -1,4 +1,4 @@
namespace ProjectSportCar.Drawnings; namespace ProjectElectroTrans.Drawnings;
/// <summary> /// <summary>
/// Направление перемещения /// Направление перемещения

View File

@ -1,5 +1,4 @@
using ProjectElectroTrans.Entities; using ProjectElectroTrans.Entities;
using ProjectSportCar.Drawnings;
namespace ProjectElectroTrans.Drawnings; namespace ProjectElectroTrans.Drawnings;

View File

@ -33,12 +33,10 @@ namespace ProjectElectroTrans
private void InitializeComponent() private void InitializeComponent()
{ {
pictureBoxElectroTrans = new PictureBox(); pictureBoxElectroTrans = new PictureBox();
buttonCreateElectroTrans = 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)pictureBoxElectroTrans).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxElectroTrans).BeginInit();
@ -53,17 +51,6 @@ namespace ProjectElectroTrans
pictureBoxElectroTrans.TabIndex = 0; pictureBoxElectroTrans.TabIndex = 0;
pictureBoxElectroTrans.TabStop = false; pictureBoxElectroTrans.TabStop = false;
// //
// buttonCreateElectroTrans
//
buttonCreateElectroTrans.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateElectroTrans.Location = new Point(12, 562);
buttonCreateElectroTrans.Name = "buttonCreateElectroTrans";
buttonCreateElectroTrans.Size = new Size(223, 23);
buttonCreateElectroTrans.TabIndex = 1;
buttonCreateElectroTrans.Text = "Создать электропоезд";
buttonCreateElectroTrans.UseVisualStyleBackColor = true;
buttonCreateElectroTrans.Click += ButtonCreateElectroTrans_Click;
//
// buttonLeft // buttonLeft
// //
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
@ -112,17 +99,6 @@ namespace ProjectElectroTrans
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(250, 562);
buttonCreateCar.Name = "buttonCreateTrans";
buttonCreateCar.Size = new Size(223, 23);
buttonCreateCar.TabIndex = 6;
buttonCreateCar.Text = "Создать поезд";
buttonCreateCar.UseVisualStyleBackColor = true;
buttonCreateCar.Click += ButtonCreateTrans_Click;
//
// comboBoxStrategy // comboBoxStrategy
// //
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList; comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
@ -143,22 +119,20 @@ namespace ProjectElectroTrans
buttonStrategyStep.UseVisualStyleBackColor = true; buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += ButtonStrategyStep_Click; buttonStrategyStep.Click += ButtonStrategyStep_Click;
// //
// FormElectroTrans // FormSportCar
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(923, 597); ClientSize = new Size(923, 597);
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(buttonCreateElectroTrans);
Controls.Add(pictureBoxElectroTrans); Controls.Add(pictureBoxElectroTrans);
Name = "FormElectroTrans"; Name = "FormElectroTrans";
Text = "Электропоезд"; Text = "Электровоз";
((System.ComponentModel.ISupportInitialize)pictureBoxElectroTrans).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxElectroTrans).EndInit();
ResumeLayout(false); ResumeLayout(false);
} }
@ -166,12 +140,10 @@ namespace ProjectElectroTrans
#endregion #endregion
private PictureBox pictureBoxElectroTrans; private PictureBox pictureBoxElectroTrans;
private Button buttonCreateElectroTrans;
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

@ -1,22 +1,41 @@
using ProjectElectroTrans.Drawnings;
using ProjectElectroTrans.MovementStrategy; using ProjectElectroTrans.MovementStrategy;
using ProjectSportCar.Drawnings; using ProjectElectroTrans.Drawnings;
using ProjectSportCar.MovementStrategy;
namespace ProjectElectroTrans; namespace ProjectElectroTrans;
/// <summary>
/// Ôîðìà ðàáîòû ñ îáúåêòîì "Ýëåêòðîïîåçä"
/// </summary>
public partial class FormElectroTrans : Form public partial class FormElectroTrans : Form
{ {
/// <summary> /// <summary>
/// Ïîëå-îáúåêò äëÿ ïðîðèñîâêè îáúåêòà /// Ïîëå-îáúåêò äëÿ ïðîðèñîâêè îáúåêòà
/// </summary> /// </summary>
private DrawingTrans? _drawingTrans; private DrawingTrans? _drawningTrans;
/// <summary> /// <summary>
/// Ñòðàòåãèÿ ïåðåìåùåíèÿ /// Ñòðàòåãèÿ ïåðåìåùåíèÿ
/// </summary> /// </summary>
private AbstractStrategy? _strategy; private AbstractStrategy? _strategy;
/// <summary>
/// Ïîëó÷åíèå îáúåêòà
/// </summary>
public DrawingTrans SetCar
{
set
{
_drawningTrans = value;
_drawningTrans.SetPictureSize(pictureBoxElectroTrans.Width, pictureBoxElectroTrans.Height);
comboBoxStrategy.Enabled = true;
_strategy = null;
Draw();
}
}
/// <summary>
/// Êîíñòðóêòîð ôîðìû
/// </summary>
public FormElectroTrans() public FormElectroTrans()
{ {
InitializeComponent(); InitializeComponent();
@ -28,54 +47,17 @@ public partial class FormElectroTrans : Form
/// </summary> /// </summary>
private void Draw() private void Draw()
{ {
if (_drawingTrans == null) if (_drawningTrans == null)
{ {
return; return;
} }
Bitmap bmp = new(pictureBoxElectroTrans.Width, pictureBoxElectroTrans.Height); Bitmap bmp = new(pictureBoxElectroTrans.Width, pictureBoxElectroTrans.Height);
Graphics gr = Graphics.FromImage(bmp); Graphics gr = Graphics.FromImage(bmp);
_drawingTrans.DrawTransport(gr); _drawningTrans.DrawTransport(gr);
pictureBoxElectroTrans.Image = bmp; pictureBoxElectroTrans.Image = bmp;
} }
private void CreateObject(string type)
{
Random random = new();
switch (type)
{
case nameof(DrawingTrans):
_drawingTrans = new DrawingTrans(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(DrawingElectroTrans):
_drawingTrans = new DrawingElectroTrans(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;
}
_drawingTrans.SetPictureSize(pictureBoxElectroTrans.Width, pictureBoxElectroTrans.Height);
_drawingTrans.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 ButtonCreateElectroTrans_Click(object sender, EventArgs e) => CreateObject(nameof(DrawingElectroTrans));
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü àâòîìîáèëü"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateTrans_Click(object sender, EventArgs e) => CreateObject(nameof(DrawingTrans));
/// <summary> /// <summary>
/// Ïåðåìåùåíèå îáúåêòà ïî ôîðìå (íàæàòèå êíîïîê íàâèãàöèè) /// Ïåðåìåùåíèå îáúåêòà ïî ôîðìå (íàæàòèå êíîïîê íàâèãàöèè)
/// </summary> /// </summary>
@ -83,7 +65,7 @@ public partial class FormElectroTrans : Form
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e) private void ButtonMove_Click(object sender, EventArgs e)
{ {
if (_drawingTrans == null) if (_drawningTrans == null)
{ {
return; return;
} }
@ -93,16 +75,16 @@ public partial class FormElectroTrans : Form
switch (name) switch (name)
{ {
case "buttonUp": case "buttonUp":
result = _drawingTrans.MoveTransport(DirectionType.Up); result = _drawningTrans.MoveTransport(DirectionType.Up);
break; break;
case "buttonDown": case "buttonDown":
result = _drawingTrans.MoveTransport(DirectionType.Down); result = _drawningTrans.MoveTransport(DirectionType.Down);
break; break;
case "buttonLeft": case "buttonLeft":
result = _drawingTrans.MoveTransport(DirectionType.Left); result = _drawningTrans.MoveTransport(DirectionType.Left);
break; break;
case "buttonRight": case "buttonRight":
result = _drawingTrans.MoveTransport(DirectionType.Right); result = _drawningTrans.MoveTransport(DirectionType.Right);
break; break;
} }
@ -111,6 +93,7 @@ public partial class FormElectroTrans : Form
Draw(); Draw();
} }
} }
/// <summary> /// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Øàã" /// Îáðàáîòêà íàæàòèÿ êíîïêè "Øàã"
/// </summary> /// </summary>
@ -118,7 +101,7 @@ public partial class FormElectroTrans : Form
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonStrategyStep_Click(object sender, EventArgs e) private void ButtonStrategyStep_Click(object sender, EventArgs e)
{ {
if (_drawingTrans == null) if (_drawningTrans == null)
{ {
return; return;
} }
@ -135,7 +118,7 @@ public partial class FormElectroTrans : Form
{ {
return; return;
} }
_strategy.SetData(new MoveableTrans(_drawingTrans), pictureBoxElectroTrans.Width, pictureBoxElectroTrans.Height); _strategy.SetData(new MoveableTrans(_drawningTrans), pictureBoxElectroTrans.Width, pictureBoxElectroTrans.Height);
} }
if (_strategy == null) if (_strategy == null)

View File

@ -0,0 +1,177 @@
using static System.Net.Mime.MediaTypeNames;
using System.Windows.Forms;
using System.Xml.Linq;
namespace ProjectElectroTrans
{
partial class FormTransCollection
{
/// <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();
buttonRemoveCar = new Button();
maskedTextBoxPosition = new MaskedTextBox();
buttonAddSportCar = new Button();
buttonAddCar = new Button();
comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox();
groupBoxTools.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
SuspendLayout();
//
// groupBoxTools
//
groupBoxTools.Controls.Add(buttonRefresh);
groupBoxTools.Controls.Add(buttonGoToCheck);
groupBoxTools.Controls.Add(buttonRemoveCar);
groupBoxTools.Controls.Add(maskedTextBoxPosition);
groupBoxTools.Controls.Add(buttonAddSportCar);
groupBoxTools.Controls.Add(buttonAddCar);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(783, 0);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(179, 616);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(6, 499);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(167, 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(6, 361);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(167, 40);
buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
buttonGoToCheck.Click += ButtonGoToCheck_Click;
//
// buttonRemoveCar
//
buttonRemoveCar.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveCar.Location = new Point(6, 251);
buttonRemoveCar.Name = "buttonRemoveTrans";
buttonRemoveCar.Size = new Size(167, 40);
buttonRemoveCar.TabIndex = 4;
buttonRemoveCar.Text = "Удалить поезд";
buttonRemoveCar.UseVisualStyleBackColor = true;
buttonRemoveCar.Click += ButtonRemoveTrans_Click;
//
// maskedTextBoxPosition
//
maskedTextBoxPosition.Location = new Point(6, 222);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(167, 23);
maskedTextBoxPosition.TabIndex = 3;
maskedTextBoxPosition.ValidatingType = typeof(int);
//
// buttonAddSportCar
//
buttonAddSportCar.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddSportCar.Location = new Point(6, 137);
buttonAddSportCar.Name = "buttonAddSportCar";
buttonAddSportCar.Size = new Size(167, 40);
buttonAddSportCar.TabIndex = 2;
buttonAddSportCar.Text = "Добавление спортивного поезда";
buttonAddSportCar.UseVisualStyleBackColor = true;
buttonAddSportCar.Click += ButtonAddElectroTrans_Click;
//
// buttonAddCar
//
buttonAddCar.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddCar.Location = new Point(6, 91);
buttonAddCar.Name = "buttonAddCar";
buttonAddCar.Size = new Size(167, 40);
buttonAddCar.TabIndex = 1;
buttonAddCar.Text = "Добавление поезда";
buttonAddCar.UseVisualStyleBackColor = true;
buttonAddCar.Click += ButtonAddTrans_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(6, 22);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(167, 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(783, 616);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
// FormCarCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(962, 616);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Name = "FormCarCollection";
Text = "Коллекция автомобилей";
groupBoxTools.ResumeLayout(false);
groupBoxTools.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
ResumeLayout(false);
}
#endregion
private GroupBox groupBoxTools;
private ComboBox comboBoxSelectorCompany;
private Button buttonAddSportCar;
private Button buttonAddCar;
private Button buttonRemoveCar;
private MaskedTextBox maskedTextBoxPosition;
private PictureBox pictureBox;
private Button buttonGoToCheck;
private Button buttonRefresh;
}
}

View File

@ -0,0 +1,190 @@
using ProjectElectroTrans.CollectionGenericObjects;
using ProjectElectroTrans.Drawnings;
using System.Windows.Forms;
namespace ProjectElectroTrans;
/// <summary>
/// Форма работы с компанией и ее коллекцией
/// </summary>
public partial class FormTransCollection : Form
{
/// <summary>
/// Компания
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Конструктор
/// </summary>
public FormTransCollection()
{
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 TransDepoService(pictureBox.Width, pictureBox.Height, new MassiveGenericObjects<DrawingTrans>());
break;
}
}
/// <summary>
/// Добавление обычного автомобиля
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddTrans_Click(object sender, EventArgs e) => CreateObject(nameof(DrawingTrans));
/// <summary>
/// Добавление спортивного автомобиля
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddElectroTrans_Click(object sender, EventArgs e) => CreateObject(nameof(DrawingElectroTrans));
/// <summary>
/// Создание объекта класса-перемещения
/// </summary>
/// <param name="type">Тип создаваемого объекта</param>
private void CreateObject(string type)
{
if (_company == null)
{
return;
}
Random random = new();
DrawingTrans drawingTrans;
switch (type)
{
case nameof(DrawingTrans):
drawingTrans = new DrawingTrans(random.Next(100, 300), random.Next(1000, 3000), GetColor(random));
break;
case nameof(DrawingElectroTrans):
// TODO вызов диалогового окна для выбора цвета
drawingTrans = new DrawingElectroTrans(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 + drawingTrans)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
}
else
{
_ = MessageBox.Show(drawingTrans.ToString());
}
}
/// <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 ButtonRemoveTrans_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)
{
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;
}
DrawingTrans? car = null;
int counter = 100;
while (car == null)
{
car = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
}
if (car == null)
{
return;
}
FormElectroTrans form = new()
{
SetCar = car
};
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,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

@ -1,6 +1,4 @@
using ProjectElectroTrans.MovementStrategy; namespace ProjectElectroTrans.MovementStrategy;
namespace ProjectSportCar.MovementStrategy;
public class MoveToBorder : AbstractStrategy public class MoveToBorder : AbstractStrategy
{ {

View File

@ -1,5 +1,4 @@
using ProjectElectroTrans.Drawnings; using ProjectElectroTrans.Drawnings;
using ProjectSportCar.Drawnings;
namespace ProjectElectroTrans.MovementStrategy; namespace ProjectElectroTrans.MovementStrategy;

View File

@ -1,3 +1,5 @@
using System.Drawing;
namespace ProjectElectroTrans namespace ProjectElectroTrans
{ {
internal static class Program internal static class Program
@ -11,7 +13,8 @@ namespace ProjectElectroTrans
// 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 FormElectroTrans()); Application.Run(new FormTransCollection());
} }
} }
} }