Залил лаб3

This commit is contained in:
ujijrujijr 2023-10-25 20:28:25 +03:00
parent 77ea779c6b
commit 3e84994000
8 changed files with 661 additions and 5 deletions

View File

@ -0,0 +1,156 @@
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
{
/// <summary>
/// Параметризованный класс для набора объектов DrawingBus
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
internal class BusesGenericCollection <T, U>
where T : DrawingBus
where U : IMoveableObject
{
/// <summary>
/// Ширина окна прорисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна прорисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Размер занимаемого объектом места (ширина)
/// </summary>
private readonly int _placeSizeWidth = 150;
/// <summary>
/// Размер занимаемого объектом места (высота)
/// </summary>
private readonly int _placeSizeHeight = 95;
/// <summary>
/// Набор объектов
/// </summary>
private readonly SetGeneric<T> _collection;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
public BusesGenericCollection(int picWidth, int picHeight)
{
int width = picWidth / _placeSizeWidth; //width - кол-во помещаемых на PictureBox автобусов по горизонтали
int height = picHeight / _placeSizeHeight; //height - кол-во помещаемых на PictureBox автобусов по вертикали
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = new SetGeneric<T>(width * height); //width*height - кол-во мест на PictureBox для автобусов; размер массива
}
/// <summary>
/// Перегрузка оператора сложения
/// </summary>
/// <param name="collect"></param>
/// <param name="obj"></param>
/// <returns></returns>
//Возвращается место в коллекции, в которое добавлено
public static int operator +(BusesGenericCollection<T, U> collect, T? obj)
{
if (obj == null)
{
return -1;
}
return collect._collection.Insert(obj);
}
/// <summary>
/// Перегрузка оператора вычитания
/// </summary>
/// <param name="collect"></param>
/// <param name="pos"></param>
/// <returns></returns>
public static bool operator -(BusesGenericCollection<T, U> collect, int pos)
{
T? obj = collect._collection.Get(pos);
if (obj != null)
{
collect._collection.Remove(pos);
return true;
}
return false;
}
/// <summary>
/// Получение объекта IMoveableObject
/// </summary>
/// <param name="pos"></param>
/// <returns></returns>
public U? GetU(int pos)
{
return (U?)_collection.Get(pos)?.GetMoveableObject;
}
/// <summary>
/// Вывод всего набора объектов
/// </summary>
/// <returns></returns>
public Bitmap ShowBuses()
{
Bitmap bmp = new(_pictureWidth, _pictureHeight);
Graphics gr = Graphics.FromImage(bmp);
DrawBackground(gr);
DrawObjects(gr);
return bmp;
}
/// <summary>
/// Метод отрисовки фона
/// </summary>
/// <param name="g"></param>
private void DrawBackground(Graphics g)
{
Pen pen = new(Color.Black, 3);
//вертикальные линии
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
g.DrawLine(pen, i * (_placeSizeWidth + 10), 0, i * (_placeSizeWidth + 10), (_pictureHeight / _placeSizeHeight) * (_placeSizeHeight + 10));
}
//горизонтальные линии
for (int i = 0; i <= _pictureHeight / _placeSizeHeight; i++)
{
for (int j = 0; j < _pictureWidth / _placeSizeWidth; j++)
{
g.DrawLine(pen, j * (_placeSizeWidth + 10), i * (_placeSizeHeight + 10), j * (_placeSizeWidth + 10) + _placeSizeWidth / 2, i * (_placeSizeHeight + 10));
}
}
}
/// <summary>
/// Метод прорисовки объектов
/// </summary>
/// <param name="g"></param>
private void DrawObjects(Graphics g)
{
int i = 0;
int j = _pictureWidth / _placeSizeWidth - 1;
for (int k = 0; k < _collection.Count; k++)
{
DrawingBus bus = _collection.Get(k);
if (bus != null)
{
bus.SetPosition(j * (_placeSizeWidth + 10) + 5, i * (_placeSizeHeight) + 10);
bus.DrawTransport(g);
}
j--;
//переход на новую строчку
if (j < 0)
{
j = _pictureWidth / _placeSizeWidth - 1;
i++;
}
}
}
}
}

View File

@ -4,6 +4,7 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Trolleybus.Entities;
using Trolleybus.MovementStrategy;
namespace Trolleybus.DrawingObjects
{
@ -56,6 +57,10 @@ namespace Trolleybus.DrawingObjects
/// Высота объекта
/// </summary>
public int GetHeight => _busHeight;
/// <summary>
/// Получение объекта IMoveableObject из объекта DrawningBus
/// </summary>
public IMoveableObject GetMoveableObject => new DrawingObjectBus(this);
/// <summary>
/// Конструктор

View File

@ -0,0 +1,181 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Trolleybus.DrawingObjects;
using Trolleybus.Generics;
using Trolleybus.MovementStrategy;
namespace Trolleybus
{
/// <summary>
/// Форма для работы с набором объектов класса DrawingBus
/// </summary>
public partial class FormBusesCollection : Form
{
/// <summary>
/// Набор объектов
/// </summary>
private readonly BusesGenericCollection<DrawingBus, DrawingObjectBus> _buses;
/// <summary>
/// Конструктор
/// </summary>
public FormBusesCollection()
{
InitializeComponent();
_buses = new BusesGenericCollection<DrawingBus, DrawingObjectBus>(pictureBoxCollection.Width, pictureBoxCollection.Height);
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddBus_Click(object sender, EventArgs e)
{
FormTrolleybus form = new FormTrolleybus();
if (form.ShowDialog() == DialogResult.OK)
{
if (_buses + form.SelectedBus != -1)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = _buses.ShowBuses();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
}
/// <summary>
/// Удаление объекта из набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveBus_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
String pos_string = maskedTextBoxNumber.Text;
if (pos_string == "")
{
pos_string = "0";
}
int pos = Convert.ToInt32(pos_string);
if (_buses - pos)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = _buses.ShowBuses();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
/// <summary>
/// Обновление рисунка по набору
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
{
pictureBoxCollection.Image = _buses.ShowBuses();
}
private void InitializeComponent()
{
pictureBoxCollection = new PictureBox();
panelTools = new Panel();
buttonRefreshCollection = new Button();
maskedTextBoxNumber = new MaskedTextBox();
buttonRemoveBus = new Button();
buttonAddBus = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
panelTools.SuspendLayout();
SuspendLayout();
//
// pictureBoxCollection
//
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.TabIndex = 0;
pictureBoxCollection.TabStop = false;
//
// panelTools
//
panelTools.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Right;
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.TabIndex = 1;
//
// buttonRefreshCollection
//
buttonRefreshCollection.Location = new Point(17, 190);
buttonRefreshCollection.Name = "buttonRefreshCollection";
buttonRefreshCollection.Size = new Size(170, 40);
buttonRefreshCollection.TabIndex = 3;
buttonRefreshCollection.Text = "Обновить коллекцию";
buttonRefreshCollection.UseVisualStyleBackColor = true;
buttonRefreshCollection.Click += ButtonRefreshCollection_Click;
//
// maskedTextBoxNumber
//
maskedTextBoxNumber.Location = new Point(39, 76);
maskedTextBoxNumber.Mask = "00";
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(125, 27);
maskedTextBoxNumber.TabIndex = 2;
maskedTextBoxNumber.ValidatingType = typeof(int);
//
// buttonRemoveBus
//
buttonRemoveBus.Location = new Point(17, 125);
buttonRemoveBus.Name = "buttonRemoveBus";
buttonRemoveBus.Size = new Size(170, 40);
buttonRemoveBus.TabIndex = 1;
buttonRemoveBus.Text = "Удалить автобус";
buttonRemoveBus.UseVisualStyleBackColor = true;
buttonRemoveBus.Click += ButtonRemoveBus_Click;
//
// buttonAddBus
//
buttonAddBus.Location = new Point(17, 12);
buttonAddBus.Name = "buttonAddBus";
buttonAddBus.Size = new Size(170, 40);
buttonAddBus.TabIndex = 0;
buttonAddBus.Text = "Добавить автобус";
buttonAddBus.UseVisualStyleBackColor = true;
buttonAddBus.Click += ButtonAddBus_Click;
//
// FormBusCollection
//
ClientSize = new Size(882, 453);
Controls.Add(panelTools);
Controls.Add(pictureBoxCollection);
Name = "FormBusCollection";
Text = "Набор автобусов";
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
panelTools.ResumeLayout(false);
panelTools.PerformLayout();
ResumeLayout(false);
}
private PictureBox pictureBoxCollection;
private Panel panelTools;
private Button buttonRefreshCollection;
private MaskedTextBox maskedTextBoxNumber;
private Button buttonRemoveBus;
private Button buttonAddBus;
}
}

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

@ -37,6 +37,7 @@
buttonCreateBus = new Button();
comboBoxStrategy = new ComboBox();
buttonStep = new Button();
buttonSelectBus = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxTrolleybus).BeginInit();
SuspendLayout();
//
@ -141,11 +142,23 @@
buttonStep.UseVisualStyleBackColor = true;
buttonStep.Click += ButtonStep_Click;
//
// buttonSelectBus
//
buttonSelectBus.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonSelectBus.Location = new Point(264, 388);
buttonSelectBus.Name = "buttonSelectBus";
buttonSelectBus.Size = new Size(120, 50);
buttonSelectBus.TabIndex = 14;
buttonSelectBus.Text = "Выбрать";
buttonSelectBus.UseVisualStyleBackColor = true;
buttonSelectBus.Click += ButtonSelectBus_Click;
//
// FormTrolleybus
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(882, 453);
Controls.Add(buttonSelectBus);
Controls.Add(buttonStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateBus);
@ -172,5 +185,6 @@
private Button buttonCreateBus;
private ComboBox comboBoxStrategy;
private Button buttonStep;
private Button buttonSelectBus;
}
}

View File

@ -16,9 +16,16 @@ namespace Trolleybus
/// Ñòðàòåãèÿ ïåðåìåùåíèÿ
/// </summary>
private AbstractStrategy? _abstractStrategy;
/// <summary>
/// Âűáđŕííűé ŕâňîáóń
/// </summary>
public DrawingBus? SelectedBus { get; private set; }
public FormTrolleybus()
{
InitializeComponent();
_abstractStrategy = null;
SelectedBus = null;
}
/// <summary>
/// Ìåòîä ïðîðèñîâêè òðîëëåéáóñà
@ -42,10 +49,26 @@ namespace Trolleybus
private void ButtonCreateTrolleybus_Click(object sender, EventArgs e)
{
Random random = new();
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;
}
Color dopColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
//âűáîđ äîďîëíčňĺëüíîăî öâĺňŕ
ColorDialog dopDialog = new();
if (dopDialog.ShowDialog() == DialogResult.OK)
{
dopColor = dopDialog.Color;
}
_drawingBus = new DrawingTrolleybus(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)),
color,
dopColor,
Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)),
pictureBoxTrolleybus.Width, pictureBoxTrolleybus.Height);
@ -61,10 +84,16 @@ namespace Trolleybus
private void ButtonCreateBus_Click(object sender, EventArgs e)
{
Random random = new();
//âűáîđ öâĺňŕ
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;
}
_drawingBus = new DrawingBus(random.Next(100, 300),
random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256),
random.Next(0, 256)),
color,
pictureBoxTrolleybus.Width, pictureBoxTrolleybus.Height);
_drawingBus.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
@ -138,5 +167,16 @@ namespace Trolleybus
_abstractStrategy = null;
}
}
/// <summary>
/// Âűáîđ ŕâňîáóńŕ
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSelectBus_Click(object sender, EventArgs e)
{
SelectedBus = _drawingBus;
DialogResult = DialogResult.OK;
}
}
}

View File

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

View File

@ -0,0 +1,140 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Trolleybus.Generics
{
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T"></typeparam>
internal class SetGeneric<T>
where T : class
{
/// <summary>
/// Массив объектов, которые храним
/// </summary>
private readonly T?[] _places;
/// <summary>
/// Количество объектов в массиве
/// </summary>
public int Count => _places.Length;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetGeneric(int count)
{
_places = new T?[count];
}
/// <summary>
/// Добавление объекта в начало набора
/// </summary>
/// <param name="bus">Добавляемый автобус</param>
/// <returns></returns>
public int Insert(T bus)
{
if (_places[0] == null)
{
_places[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;
}
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="bus">Добавляемый автобус</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public int Insert(T bus, int position)
{
if (position >= Count || position < 0)
{
//индекс неверный, значит вставить по индексу нельзя
return -1;
}
if (_places[position] == null)
{
_places[position] = bus;
}
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;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public bool Remove(int position)
{
if (position >= Count || position < 0)
{
return false;
}
_places[position] = null;
return true;
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T? Get(int position)
{
if (position >= Count || position < 0)
{
return null;
}
return _places[position];
}
}
}