Готовая 3 лабораторная

This commit is contained in:
Илья 2023-10-10 14:57:21 +04:00
parent fcf35359c7
commit 656f12f9a9
9 changed files with 694 additions and 14 deletions

View File

@ -1,4 +1,5 @@
using ProjectMonorail.Entities; using ProjectMonorail.Entities;
using ProjectMonorail.MovementStrategy;
namespace ProjectMonorail.DrawingObjects namespace ProjectMonorail.DrawingObjects
{ {
@ -62,6 +63,11 @@ namespace ProjectMonorail.DrawingObjects
/// </summary> /// </summary>
public int GetHeight => _monorailHeight; public int GetHeight => _monorailHeight;
/// <summary>
/// Получение объекта IMoveableObject из объекта DrawingMonorail
/// </summary>
public IMoveableObject GetMoveableObject => new DrawingObjectMonorail(this);
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
@ -188,6 +194,10 @@ namespace ProjectMonorail.DrawingObjects
Brush brWhite = new SolidBrush(Color.White); Brush brWhite = new SolidBrush(Color.White);
Brush brGray = new SolidBrush(Color.Gray); Brush brGray = new SolidBrush(Color.Gray);
//надстройка
g.FillRectangle(mainBrush, _startPosX + 55, _startPosY, 25, 15);
g.DrawRectangle(mainPen, _startPosX + 55, _startPosY, 25, 15);
//корпус локомотива //корпус локомотива
Point[] locoPoints = { new Point(_startPosX + 29, _startPosY + 15), new Point(_startPosX + 112, _startPosY + 15), Point[] locoPoints = { new Point(_startPosX + 29, _startPosY + 15), new Point(_startPosX + 112, _startPosY + 15),
new Point(_startPosX + 112, _startPosY + 46), new Point(_startPosX + 25, _startPosY + 46), new Point(_startPosX + 25, _startPosY + 31) }; new Point(_startPosX + 112, _startPosY + 46), new Point(_startPosX + 25, _startPosY + 46), new Point(_startPosX + 25, _startPosY + 31) };

View File

@ -37,6 +37,7 @@
comboBoxStrategy = new ComboBox(); comboBoxStrategy = new ComboBox();
buttonCreateMonorail = new Button(); buttonCreateMonorail = new Button();
buttonStep = new Button(); buttonStep = new Button();
buttonSelectMonorail = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxMonorail).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxMonorail).BeginInit();
SuspendLayout(); SuspendLayout();
// //
@ -142,11 +143,23 @@
buttonStep.UseVisualStyleBackColor = true; buttonStep.UseVisualStyleBackColor = true;
buttonStep.Click += buttonStep_Click; buttonStep.Click += buttonStep_Click;
// //
// buttonSelectMonorail
//
buttonSelectMonorail.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonSelectMonorail.Location = new Point(324, 403);
buttonSelectMonorail.Name = "buttonSelectMonorail";
buttonSelectMonorail.Size = new Size(140, 39);
buttonSelectMonorail.TabIndex = 9;
buttonSelectMonorail.Text = "Select";
buttonSelectMonorail.UseVisualStyleBackColor = true;
buttonSelectMonorail.Click += buttonSelectMonorail_Click;
//
// FormMonorail // FormMonorail
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(884, 461); ClientSize = new Size(884, 461);
Controls.Add(buttonSelectMonorail);
Controls.Add(buttonStep); Controls.Add(buttonStep);
Controls.Add(buttonCreateMonorail); Controls.Add(buttonCreateMonorail);
Controls.Add(comboBoxStrategy); Controls.Add(comboBoxStrategy);
@ -175,5 +188,6 @@
private ComboBox comboBoxStrategy; private ComboBox comboBoxStrategy;
private Button buttonCreateMonorail; private Button buttonCreateMonorail;
private Button buttonStep; private Button buttonStep;
private Button buttonSelectMonorail;
} }
} }

View File

@ -16,7 +16,12 @@ namespace ProjectMonorail
/// <summary> /// <summary>
/// Стратегия перемещения /// Стратегия перемещения
/// </summary> /// </summary>
private AbstractStrategy? _abstractStrategy; private AbstractStrategy? _strategy;
/// <summary>
/// Выбранный монорельс
/// </summary>
public DrawingMonorail? SelectedMonorail { get; private set; }
/// <summary> /// <summary>
/// Инициализация формы /// Инициализация формы
@ -24,6 +29,8 @@ namespace ProjectMonorail
public FormMonorail() public FormMonorail()
{ {
InitializeComponent(); InitializeComponent();
_strategy = null;
SelectedMonorail = null;
} }
/// <summary> /// <summary>
@ -49,8 +56,21 @@ namespace ProjectMonorail
private void buttonCreateExtendedMonorail_Click(object sender, EventArgs e) private void buttonCreateExtendedMonorail_Click(object sender, EventArgs e)
{ {
Random random = new(); Random random = new();
_drawingMonorail = new DrawingExtendedMonorail(random.Next(200, 400), random.Next(1000, 3000), Color.FromArgb(random.Next(0, 256), Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), 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)), ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
Color additionalColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
ColorDialog additionalDialog = new();
if (additionalDialog.ShowDialog() == DialogResult.OK)
{
additionalColor = additionalDialog.Color;
}
_drawingMonorail = new DrawingExtendedMonorail(random.Next(200, 400), random.Next(1000, 3000), color, additionalColor,
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)), pictureBoxMonorail.Width, pictureBoxMonorail.Height); Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)), pictureBoxMonorail.Width, pictureBoxMonorail.Height);
_drawingMonorail.SetPosition(random.Next(10, 100), random.Next(10, 100)); _drawingMonorail.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw(); Draw();
@ -64,8 +84,13 @@ namespace ProjectMonorail
private void buttonCreateMonorail_Click(object sender, EventArgs e) private void buttonCreateMonorail_Click(object sender, EventArgs e)
{ {
Random random = new(); Random random = new();
_drawingMonorail = new DrawingMonorail(random.Next(200, 400), random.Next(1000, 3000), Color.FromArgb(random.Next(0, 256), random.Next(0, 256), Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
random.Next(0, 256)), pictureBoxMonorail.Width, pictureBoxMonorail.Height); ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
_drawingMonorail = new DrawingMonorail(random.Next(200, 400), random.Next(1000, 3000), color, pictureBoxMonorail.Width, pictureBoxMonorail.Height);
_drawingMonorail.SetPosition(random.Next(10, 100), random.Next(10, 100)); _drawingMonorail.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw(); Draw();
} }
@ -113,31 +138,42 @@ namespace ProjectMonorail
} }
if (comboBoxStrategy.Enabled) if (comboBoxStrategy.Enabled)
{ {
_abstractStrategy = comboBoxStrategy.SelectedIndex _strategy = comboBoxStrategy.SelectedIndex
switch switch
{ {
0 => new MoveToCenter(), 0 => new MoveToCenter(),
1 => new MoveToBorder(), 1 => new MoveToBorder(),
_ => null, _ => null,
}; };
if (_abstractStrategy == null) if (_strategy == null)
{
return;
}
_strategy.SetData(new DrawingObjectMonorail(_drawingMonorail), pictureBoxMonorail.Width, pictureBoxMonorail.Height);
}
if (_strategy == null)
{ {
return; return;
} }
_abstractStrategy.SetData(new DrawingObjectMonorail(_drawingMonorail), pictureBoxMonorail.Width, pictureBoxMonorail.Height);
comboBoxStrategy.Enabled = false; comboBoxStrategy.Enabled = false;
} _strategy.MakeStep();
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.MakeStep();
Draw(); Draw();
if (_abstractStrategy.GetStatus() == Status.Finish) if (_strategy.GetStatus() == Status.Finish)
{ {
comboBoxStrategy.Enabled = true; comboBoxStrategy.Enabled = true;
_abstractStrategy = null; _strategy = null;
} }
} }
/// <summary>
/// Выбор монорельса
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSelectMonorail_Click(object sender, EventArgs e)
{
SelectedMonorail = _drawingMonorail;
DialogResult = DialogResult.OK;
}
} }
} }

View File

@ -0,0 +1,149 @@
namespace ProjectMonorail
{
partial class FormMonorailCollection
{
/// <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()
{
panelTools = new Panel();
buttonRefreshCollection = new Button();
labelName = new Label();
maskedTextBoxNumber = new MaskedTextBox();
buttonRemoveMonorail = new Button();
buttonAddMonorail = new Button();
pictureBoxCollection = new PictureBox();
panelTools.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
SuspendLayout();
//
// panelTools
//
panelTools.Anchor = AnchorStyles.Top | AnchorStyles.Right;
panelTools.BorderStyle = BorderStyle.FixedSingle;
panelTools.Controls.Add(buttonRefreshCollection);
panelTools.Controls.Add(labelName);
panelTools.Controls.Add(maskedTextBoxNumber);
panelTools.Controls.Add(buttonRemoveMonorail);
panelTools.Controls.Add(buttonAddMonorail);
panelTools.Location = new Point(788, 10);
panelTools.Name = "panelTools";
panelTools.Size = new Size(186, 430);
panelTools.TabIndex = 0;
//
// buttonRefreshCollection
//
buttonRefreshCollection.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonRefreshCollection.BackColor = SystemColors.Window;
buttonRefreshCollection.FlatAppearance.BorderColor = Color.Black;
buttonRefreshCollection.FlatStyle = FlatStyle.Flat;
buttonRefreshCollection.Location = new Point(18, 281);
buttonRefreshCollection.Name = "buttonRefreshCollection";
buttonRefreshCollection.Size = new Size(155, 34);
buttonRefreshCollection.TabIndex = 3;
buttonRefreshCollection.Text = "Refresh collection";
buttonRefreshCollection.UseVisualStyleBackColor = false;
buttonRefreshCollection.Click += buttonRefreshCollection_Click;
//
// labelName
//
labelName.AutoSize = true;
labelName.Font = new Font("Segoe UI Semibold", 12F, FontStyle.Bold, GraphicsUnit.Point);
labelName.Location = new Point(17, -2);
labelName.Name = "labelName";
labelName.Size = new Size(48, 21);
labelName.TabIndex = 0;
labelName.Text = "Tools";
//
// maskedTextBoxNumber
//
maskedTextBoxNumber.BorderStyle = BorderStyle.FixedSingle;
maskedTextBoxNumber.Location = new Point(17, 144);
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(155, 23);
maskedTextBoxNumber.TabIndex = 2;
//
// buttonRemoveMonorail
//
buttonRemoveMonorail.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonRemoveMonorail.BackColor = SystemColors.Window;
buttonRemoveMonorail.FlatAppearance.BorderColor = Color.Black;
buttonRemoveMonorail.FlatStyle = FlatStyle.Flat;
buttonRemoveMonorail.Location = new Point(18, 173);
buttonRemoveMonorail.Name = "buttonRemoveMonorail";
buttonRemoveMonorail.Size = new Size(155, 34);
buttonRemoveMonorail.TabIndex = 1;
buttonRemoveMonorail.Text = "Remove monorail";
buttonRemoveMonorail.UseVisualStyleBackColor = false;
buttonRemoveMonorail.Click += buttonRemoveMonorail_Click;
//
// buttonAddMonorail
//
buttonAddMonorail.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonAddMonorail.BackColor = SystemColors.Window;
buttonAddMonorail.FlatAppearance.BorderColor = Color.Black;
buttonAddMonorail.FlatStyle = FlatStyle.Flat;
buttonAddMonorail.Location = new Point(18, 33);
buttonAddMonorail.Name = "buttonAddMonorail";
buttonAddMonorail.Size = new Size(155, 34);
buttonAddMonorail.TabIndex = 0;
buttonAddMonorail.Text = "Add monorail";
buttonAddMonorail.UseVisualStyleBackColor = false;
buttonAddMonorail.Click += buttonAddMonorail_Click;
//
// pictureBoxCollection
//
pictureBoxCollection.Location = new Point(5, 10);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(777, 430);
pictureBoxCollection.TabIndex = 1;
pictureBoxCollection.TabStop = false;
//
// FormMonorailCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(974, 439);
Controls.Add(pictureBoxCollection);
Controls.Add(panelTools);
Name = "FormMonorailCollection";
Text = "Monorail collection";
panelTools.ResumeLayout(false);
panelTools.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
ResumeLayout(false);
}
#endregion
private Panel panelTools;
private Label labelName;
private Button buttonAddMonorail;
private Button buttonRemoveMonorail;
private MaskedTextBox maskedTextBoxNumber;
private Button buttonRefreshCollection;
private PictureBox pictureBoxCollection;
}
}

View File

@ -0,0 +1,83 @@
using ProjectMonorail.Generics;
using ProjectMonorail.MovementStrategy;
using ProjectMonorail.DrawingObjects;
namespace ProjectMonorail
{
/// <summary>
/// Форма для работы с набором объектов класса DrawingMonorail
/// </summary>
public partial class FormMonorailCollection : Form
{
/// <summary>
/// Набор объектов
/// </summary>
private readonly MonorailsGenericCollection<DrawingMonorail, DrawingObjectMonorail> _monorails;
/// <summary>
/// Конструктор
/// </summary>
public FormMonorailCollection()
{
InitializeComponent();
_monorails = new MonorailsGenericCollection<DrawingMonorail, DrawingObjectMonorail>(pictureBoxCollection.Width, pictureBoxCollection.Height);
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAddMonorail_Click(object sender, EventArgs e)
{
FormMonorail form = new();
if (form.ShowDialog() == DialogResult.OK)
{
if (_monorails + form.SelectedMonorail != -1)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = _monorails.ShowMonorails();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
}
/// <summary>
/// Удаление объекта из набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonRemoveMonorail_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (_monorails - pos)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = _monorails.ShowMonorails();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
/// <summary>
/// Обновление рисунка по набору
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonRefreshCollection_Click(object sender, EventArgs e)
{
pictureBoxCollection.Image = _monorails.ShowMonorails();
}
}
}

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

@ -0,0 +1,155 @@
using ProjectMonorail.DrawingObjects;
using ProjectMonorail.MovementStrategy;
namespace ProjectMonorail.Generics
{
/// <summary>
/// Параметризованный класс для набора объектов
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
internal class MonorailsGenericCollection<T, U>
where T : DrawingMonorail
where U : IMoveableObject
{
/// <summary>
/// Ширина окна прорисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна прорисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Размер занимаемого объектом места (ширина)
/// </summary>
private readonly int _placeSizeWidth = 193;
/// <summary>
/// Размер занимаемого объектом места (высота)
/// </summary>
private readonly int _placeSizeHeight = 102;
/// <summary>
/// Набор объектов
/// </summary>
private readonly SetGeneric<T> _collection;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
public MonorailsGenericCollection(int picWidth, int picHeight)
{
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = new SetGeneric<T>(width * height);
}
/// <summary>
/// Перегрузка оператора сложения
/// </summary>
/// <param name="collect"></param>
/// <param name="obj"></param>
/// <returns></returns>
public static int operator +(MonorailsGenericCollection<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 -(MonorailsGenericCollection<T, U> collect, int pos)
{
T? obj = collect._collection.Get(pos);
if (obj != null)
{
return collect._collection.Remove(pos);
}
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 ShowMonorails()
{
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++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j)
{ //линия разметки места
g.DrawLine(pen, i * _placeSizeWidth, j * _placeSizeHeight, i * _placeSizeWidth
+ _placeSizeWidth / 2, j * _placeSizeHeight);
}
g.DrawLine(pen, i * _placeSizeWidth, 0, i * _placeSizeWidth,
_pictureHeight / _placeSizeHeight * _placeSizeHeight);
}
}
/// <summary>
/// Метод прорисовки объектов
/// </summary>
/// <param name="g"></param>
private void DrawObjects(Graphics g)
{
T? obj;
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
int diff = 1, currWidth = 0;
for (int i = 0; i < _collection.Count; i++)
{
currWidth++;
if (currWidth > width)
{
diff++;
currWidth = 1;
}
obj = _collection.Get(i);
if (obj != null)
{
obj.SetPosition(i % width * _placeSizeWidth + _placeSizeWidth / 40,
(height - diff) * _placeSizeHeight + _placeSizeHeight / 15);
obj.DrawTransport(g);
}
}
}
}
}

View File

@ -11,7 +11,7 @@ namespace ProjectMonorail
// 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 FormMonorail()); Application.Run(new FormMonorailCollection());
} }
} }
} }

View File

@ -0,0 +1,113 @@
namespace ProjectMonorail.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="monorail">Добавляемый монорельс</param>
/// <returns></returns>
public int Insert(T monorail)
{
int nullIndex = -1, i;
for (i = 0; i < Count; i++)
{
if (_places[i] == null)
{
nullIndex = i;
break;
}
}
if (nullIndex < 0)
return -1;
for (i = nullIndex; i > 0; i--)
{
_places[i] = _places[i - 1];
}
_places[0] = monorail;
return 0;
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="monorail">Добавляемый монорельс</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public int Insert(T monorail, int position)
{
int nullIndex = -1, i;
if (position < 0 || position >= Count)
return -1;
for (i = position; i < Count; i++)
{
if (_places[i] == null)
{
nullIndex = i;
break;
}
}
if (nullIndex < 0)
return -1;
for (i = nullIndex; i > position; i--)
{
_places[i] = _places[i - 1];
}
_places[position] = monorail;
return position;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public bool Remove(int position)
{
if (position < 0 || position >= Count)
return false;
_places[position] = null;
return true;
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T? Get(int position)
{
if (position < 0 || position >= Count)
return null;
return _places[position];
}
}
}