PIbd-22_Chernyshev_G.Y._LabWork04_Base #4

Closed
ujijrujijr wants to merge 1 commits from LabWork04 into LabWork03
5 changed files with 345 additions and 111 deletions

View File

@ -73,7 +73,7 @@ namespace Trolleybus.Generics
/// <returns></returns>
public static bool operator -(BusesGenericCollection<T, U> collect, int pos)
{
T? obj = collect._collection.Get(pos);
T? obj = collect._collection[pos];
if (obj != null)
{
collect._collection.Remove(pos);
@ -90,7 +90,7 @@ namespace Trolleybus.Generics
/// <returns></returns>
public U? GetU(int pos)
{
return (U?)_collection.Get(pos)?.GetMoveableObject;
return (U?)_collection[pos]?.GetMoveableObject;
}
/// <summary>
/// Вывод всего набора объектов
@ -134,9 +134,8 @@ namespace Trolleybus.Generics
{
int i = 0;
int j = _pictureWidth / _placeSizeWidth - 1;
for (int k = 0; k < _collection.Count; k++)
foreach (var bus in _collection.GetBuses())
{
DrawingBus bus = _collection.Get(k);
if (bus != null)
{
bus.SetPosition(j * (_placeSizeWidth + 10) + 5, i * (_placeSizeHeight) + 10);
@ -149,7 +148,6 @@ namespace Trolleybus.Generics
j = _pictureWidth / _placeSizeWidth - 1;
i++;
}
}
}
}

View File

@ -0,0 +1,89 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Trolleybus.DrawingObjects;
using Trolleybus.MovementStrategy;
namespace Trolleybus.Generics
{
internal class BusesGenericStorage
{
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<string, BusesGenericCollection<DrawingBus, DrawingObjectBus>> _busStorages;
/// <summary>
/// Возвращение списка названий наборов
/// </summary>
public List<string> Keys => _busStorages.Keys.ToList();
/// <summary>
/// Ширина окна отрисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна отрисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="pictureWidth"></param>
/// <param name="pictureHeight"></param>
public BusesGenericStorage(int pictureWidth, int pictureHeight)
{
_busStorages = new Dictionary<string, BusesGenericCollection<DrawingBus, DrawingObjectBus>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
/// <summary>
/// Добавление набора
/// </summary>
/// <param name="name">Название набора</param>
public void AddSet(string name)
{
// проверка, существует ли набор с таким ключём
if (_busStorages.ContainsKey(name))
{
return;
}
var busCollection = new BusesGenericCollection<DrawingBus, DrawingObjectBus>(_pictureWidth, _pictureHeight);
_busStorages.Add(name, busCollection);
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="name">Название набора</param>
public void DelSet(string name)
{
if (_busStorages.ContainsKey(name))
{
_busStorages.Remove(name);
}
}
/// <summary>
/// Доступ к набору
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public BusesGenericCollection<DrawingBus, DrawingObjectBus>? this[string ind]
{
get
{
if (!_busStorages.ContainsKey(ind))
{
return null;
}
return _busStorages[ind];
}
}
}
}

View File

@ -18,14 +18,78 @@ namespace Trolleybus
/// <summary>
/// Набор объектов
/// </summary>
private readonly BusesGenericCollection<DrawingBus, DrawingObjectBus> _buses;
private readonly BusesGenericStorage _storage;
/// <summary>
/// Конструктор
/// </summary>
public FormBusesCollection()
{
InitializeComponent();
_buses = new BusesGenericCollection<DrawingBus, DrawingObjectBus>(pictureBoxCollection.Width, pictureBoxCollection.Height);
_storage = new BusesGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
}
/// <summary>
/// Заполнение listBoxObjects
/// </summary>
private void ReloadObjects()
{
int index = listBoxSets.SelectedIndex;
listBoxSets.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++)
{
listBoxSets.Items.Add(_storage.Keys[i]);
}
if (listBoxSets.Items.Count > 0 && (index == -1 || index >= listBoxSets.Items.Count))
{
listBoxSets.SelectedIndex = 0;
}
else if (listBoxSets.Items.Count > 0 && index > -1 && index < listBoxSets.Items.Count)
{
listBoxSets.SelectedIndex = index;
}
}
/// <summary>
/// Добавление набора в коллекцию
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddSetOfObjects_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxNameOfSet.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_storage.AddSet(textBoxNameOfSet.Text);
ReloadObjects();
}
/// <summary>
/// Выбор набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ListBoxSets_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBoxCollection.Image = _storage[listBoxSets.SelectedItem?.ToString() ?? string.Empty]?.ShowBuses();
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonDeleteSetOfObjects_Click(object sender, EventArgs e)
{
if (listBoxSets.SelectedIndex == -1)
{
return;
}
if (MessageBox.Show($"Удалить объект {listBoxSets.SelectedItem}?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(listBoxSets.SelectedItem.ToString() ?? string.Empty);
ReloadObjects();
}
}
/// <summary>
/// Добавление объекта в набор
@ -34,13 +98,23 @@ namespace Trolleybus
/// <param name="e"></param>
private void ButtonAddBus_Click(object sender, EventArgs e)
{
if (listBoxSets.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxSets.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
FormTrolleybus form = new FormTrolleybus();
if (form.ShowDialog() == DialogResult.OK)
{
if (_buses + form.SelectedBus != -1)
if (obj + form.SelectedBus != -1)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = _buses.ShowBuses();
pictureBoxCollection.Image = obj.ShowBuses();
}
else
{
@ -55,6 +129,15 @@ namespace Trolleybus
/// <param name="e"></param>
private void ButtonRemoveBus_Click(object sender, EventArgs e)
{
if (listBoxSets.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxSets.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
@ -66,10 +149,10 @@ namespace Trolleybus
pos_string = "0";
}
int pos = Convert.ToInt32(pos_string);
if (_buses - pos)
if (obj - pos)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = _buses.ShowBuses();
pictureBoxCollection.Image = obj.ShowBuses();
}
else
{
@ -83,19 +166,34 @@ namespace Trolleybus
/// <param name="e"></param>
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
{
pictureBoxCollection.Image = _buses.ShowBuses();
if (listBoxSets.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxSets.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
pictureBoxCollection.Image = obj.ShowBuses();
}
private void InitializeComponent()
{
pictureBoxCollection = new PictureBox();
panelTools = new Panel();
panelSets = new Panel();
buttonDeleteSetOfObjects = new Button();
textBoxNameOfSet = new TextBox();
listBoxSets = new ListBox();
buttonAddSetOfObjects = new Button();
buttonRefreshCollection = new Button();
maskedTextBoxNumber = new MaskedTextBox();
buttonRemoveBus = new Button();
buttonAddBus = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
panelTools.SuspendLayout();
panelSets.SuspendLayout();
SuspendLayout();
//
// pictureBoxCollection
@ -103,25 +201,77 @@ namespace Trolleybus
pictureBoxCollection.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
pictureBoxCollection.Location = new Point(0, 0);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(670, 453);
pictureBoxCollection.Size = new Size(670, 553);
pictureBoxCollection.TabIndex = 0;
pictureBoxCollection.TabStop = false;
//
// panelTools
//
panelTools.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Right;
panelTools.BorderStyle = BorderStyle.FixedSingle;
panelTools.Controls.Add(panelSets);
panelTools.Controls.Add(buttonRefreshCollection);
panelTools.Controls.Add(maskedTextBoxNumber);
panelTools.Controls.Add(buttonRemoveBus);
panelTools.Controls.Add(buttonAddBus);
panelTools.Location = new Point(682, 0);
panelTools.Name = "panelTools";
panelTools.Size = new Size(200, 453);
panelTools.Size = new Size(200, 553);
panelTools.TabIndex = 1;
//
// panelSets
//
panelSets.Anchor = AnchorStyles.Top | AnchorStyles.Right;
panelSets.BorderStyle = BorderStyle.FixedSingle;
panelSets.Controls.Add(buttonDeleteSetOfObjects);
panelSets.Controls.Add(textBoxNameOfSet);
panelSets.Controls.Add(listBoxSets);
panelSets.Controls.Add(buttonAddSetOfObjects);
panelSets.Location = new Point(17, 11);
panelSets.Name = "panelSets";
panelSets.Size = new Size(170, 283);
panelSets.TabIndex = 4;
//
// buttonDeleteSetOfObjects
//
buttonDeleteSetOfObjects.Location = new Point(3, 222);
buttonDeleteSetOfObjects.Name = "buttonDeleteSetOfObjects";
buttonDeleteSetOfObjects.Size = new Size(162, 45);
buttonDeleteSetOfObjects.TabIndex = 3;
buttonDeleteSetOfObjects.Text = "Удалить набор";
buttonDeleteSetOfObjects.UseVisualStyleBackColor = true;
buttonDeleteSetOfObjects.Click += ButtonDeleteSetOfObjects_Click;
//
// textBoxNameOfSet
//
textBoxNameOfSet.Location = new Point(3, 19);
textBoxNameOfSet.Name = "textBoxNameOfSet";
textBoxNameOfSet.Size = new Size(162, 27);
textBoxNameOfSet.TabIndex = 2;
//
// listBoxSets
//
listBoxSets.FormattingEnabled = true;
listBoxSets.ItemHeight = 20;
listBoxSets.Location = new Point(3, 112);
listBoxSets.Name = "listBoxSets";
listBoxSets.Size = new Size(162, 104);
listBoxSets.TabIndex = 1;
listBoxSets.SelectedIndexChanged += ListBoxSets_SelectedIndexChanged;
//
// buttonAddSetOfObjects
//
buttonAddSetOfObjects.Location = new Point(3, 52);
buttonAddSetOfObjects.Name = "buttonAddSetOfObjects";
buttonAddSetOfObjects.Size = new Size(162, 45);
buttonAddSetOfObjects.TabIndex = 0;
buttonAddSetOfObjects.Text = "Добавить набор";
buttonAddSetOfObjects.UseVisualStyleBackColor = true;
buttonAddSetOfObjects.Click += ButtonAddSetOfObjects_Click;
//
// buttonRefreshCollection
//
buttonRefreshCollection.Location = new Point(17, 190);
buttonRefreshCollection.Location = new Point(17, 484);
buttonRefreshCollection.Name = "buttonRefreshCollection";
buttonRefreshCollection.Size = new Size(170, 40);
buttonRefreshCollection.TabIndex = 3;
@ -131,7 +281,7 @@ namespace Trolleybus
//
// maskedTextBoxNumber
//
maskedTextBoxNumber.Location = new Point(39, 76);
maskedTextBoxNumber.Location = new Point(39, 366);
maskedTextBoxNumber.Mask = "00";
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(125, 27);
@ -140,7 +290,7 @@ namespace Trolleybus
//
// buttonRemoveBus
//
buttonRemoveBus.Location = new Point(17, 125);
buttonRemoveBus.Location = new Point(17, 409);
buttonRemoveBus.Name = "buttonRemoveBus";
buttonRemoveBus.Size = new Size(170, 40);
buttonRemoveBus.TabIndex = 1;
@ -150,7 +300,7 @@ namespace Trolleybus
//
// buttonAddBus
//
buttonAddBus.Location = new Point(17, 12);
buttonAddBus.Location = new Point(17, 311);
buttonAddBus.Name = "buttonAddBus";
buttonAddBus.Size = new Size(170, 40);
buttonAddBus.TabIndex = 0;
@ -158,16 +308,18 @@ namespace Trolleybus
buttonAddBus.UseVisualStyleBackColor = true;
buttonAddBus.Click += ButtonAddBus_Click;
//
// FormBusCollection
// FormBusesCollection
//
ClientSize = new Size(882, 453);
ClientSize = new Size(882, 553);
Controls.Add(panelTools);
Controls.Add(pictureBoxCollection);
Name = "FormBusCollection";
Name = "FormBusesCollection";
Text = "Набор автобусов";
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
panelTools.ResumeLayout(false);
panelTools.PerformLayout();
panelSets.ResumeLayout(false);
panelSets.PerformLayout();
ResumeLayout(false);
}
@ -176,6 +328,12 @@ namespace Trolleybus
private Button buttonRefreshCollection;
private MaskedTextBox maskedTextBoxNumber;
private Button buttonRemoveBus;
private Panel panelSets;
private Button buttonAddSetOfObjects;
private ListBox listBoxSets;
private TextBox textBoxNameOfSet;
private Button buttonDeleteSetOfObjects;
private Button buttonAddBus;
}
}

View File

@ -1,17 +1,17 @@
<?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
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>
@ -26,36 +26,36 @@
<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
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
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
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
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
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
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
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->

View File

@ -14,20 +14,25 @@ namespace Trolleybus.Generics
where T : class
{
/// <summary>
/// Массив объектов, которые храним
/// Список объектов, которые храним
/// </summary>
private readonly T?[] _places;
private readonly List<T>? _places;
/// <summary>
/// Количество объектов в массиве
/// Количество объектов в списке
/// </summary>
public int Count => _places.Length;
public int Count => _places.Count;
/// <summary>
/// Максимальное количество объектов в списке
/// </summary>
private readonly int _maxCount;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetGeneric(int count)
{
_places = new T?[count];
_maxCount = count;
_places = new List<T?>(count);
}
/// <summary>
/// Добавление объекта в начало набора
@ -36,35 +41,14 @@ namespace Trolleybus.Generics
/// <returns></returns>
public int Insert(T bus)
{
if (_places[0] == null)
if (Count + 1 <= _maxCount)
{
_places[0] = bus;
//0 в данном случае - индекс в массиве, вставка прошла успешно
_places.Insert(0, bus);
//0 в данном случае место, на котоорое добавился элемннт, вставка прошла успешно
return 0;
}
else
{
int index = 0;
while (_places[index] != null)
{
index++;
if (index >= Count)
{
//места в массиве нет, ни по какому индексу вставить нельзя
return -1;
}
}
//cдвиг элементов
for (int i = index; i > 0; i--)
{
_places[i] = _places[i - 1];
}
_places[0] = bus;
//0 в данном случае - индекс в массиве, вставка прошла успешно
return 0;
}
//если при добавлении в списке станет больше макс. кол-ва элементов, то как бы вставлять будет некуда
return -1;
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
@ -74,40 +58,19 @@ namespace Trolleybus.Generics
/// <returns></returns>
public int Insert(T bus, int position)
{
if (position >= Count || position < 0)
if (position >= _maxCount || position < 0)
{
//индекс неверный, значит вставить по индексу нельзя
//позиция неверная, значит вставить нельзя
return -1;
}
if (_places[position] == null)
if (Count + 1 <= _maxCount)
{
_places[position] = bus;
_places.Insert(position, bus);
//место в списке, по которому вставили, вставка прошла успешно
return position;
}
else
{
//проверка, что в массиве после вставляемого эл-а есть место
int index = position;
while (_places[index] != null)
{
index++;
if (index >= Count)
{
//места в массиве нет, ни по какому индексу вставить нельзя
return -1;
}
}
//сдвиг элементов
for (int i = index; i > position; i--)
{
_places[i] = _places[i - 1];
}
//вставка по позиции
_places[position] = bus;
}
//индекс в массиве, по которому вставили, вставка прошла успешно
return position;
//места в списке нет
return -1;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
@ -120,7 +83,7 @@ namespace Trolleybus.Generics
{
return false;
}
_places[position] = null;
_places.RemoveAt(position);
return true;
}
/// <summary>
@ -128,13 +91,39 @@ namespace Trolleybus.Generics
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T? Get(int position)
public T? this[int position]
{
if (position >= Count || position < 0)
get
{
return null;
if (position >= Count || position < 0)
{
return null;
}
return _places[position];
}
set
{
if (position >= Count || position < 0)
{
return;
}
_places[position] = value;
}
}
/// <summary>
/// Проход по списку
/// </summary>
/// <returns></returns>
public IEnumerable<T?> GetBuses(int? maxBuses = null)
{
for (int i = 0; i < Count; ++i)
{
yield return _places[i];
if (maxBuses.HasValue && i == maxBuses.Value)
{
yield break;
}
}
return _places[position];
}
}
}