PIbd-21 Potapov N.S. LabWork03 #3

Closed
ns.potapov wants to merge 9 commits from LabWork03 into LabWork02
9 changed files with 658 additions and 23 deletions

View File

@ -235,5 +235,9 @@ namespace ProjectStormtrooper
g.FillRectangle(brushBodyColor, _startPosX + _planeWidth / 8, _startPosY + _planeHeight / 2 - bodyHeight / 2, _planeWidth - _planeWidth / 8, bodyHeight);
g.DrawRectangle(penBlack, _startPosX + _planeWidth / 8, _startPosY + _planeHeight / 2 - bodyHeight / 2, _planeWidth - _planeWidth / 8, bodyHeight);
}
/// <summary>
/// Получение объекта IMoveableObject из объекта DrawingPlane
/// </summary>
public IMoveableObject GetMoveableObject => new DrawingObjectPlane(this);
}
}

View File

@ -0,0 +1,128 @@
namespace ProjectStormtrooper
{
partial class FormPlaneCollection
{
/// <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();
maskedTextBoxNumber = new MaskedTextBox();
buttonRefreshCollection = new Button();
buttonRemovePlane = new Button();
buttonAddPlane = new Button();
pictureBoxCollection = new PictureBox();
groupBoxTools.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
SuspendLayout();
//
// groupBoxTools
//
groupBoxTools.Controls.Add(maskedTextBoxNumber);
groupBoxTools.Controls.Add(buttonRefreshCollection);
groupBoxTools.Controls.Add(buttonRemovePlane);
groupBoxTools.Controls.Add(buttonAddPlane);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(787, 0);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(230, 538);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// maskedTextBoxNumber
//
maskedTextBoxNumber.Location = new Point(6, 87);
maskedTextBoxNumber.Mask = "00";
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(218, 27);
maskedTextBoxNumber.TabIndex = 4;
maskedTextBoxNumber.TextAlign = HorizontalAlignment.Center;
maskedTextBoxNumber.ValidatingType = typeof(int);
//
// buttonRefreshCollection
//
buttonRefreshCollection.Location = new Point(6, 180);
buttonRefreshCollection.Name = "buttonRefreshCollection";
buttonRefreshCollection.Size = new Size(218, 29);
buttonRefreshCollection.TabIndex = 3;
buttonRefreshCollection.Text = "Обновить коллекцию";
buttonRefreshCollection.UseVisualStyleBackColor = true;
buttonRefreshCollection.Click += buttonRefreshCollection_Click;
//
// buttonRemovePlane
//
buttonRemovePlane.Location = new Point(6, 120);
buttonRemovePlane.Name = "buttonRemovePlane";
buttonRemovePlane.Size = new Size(218, 29);
buttonRemovePlane.TabIndex = 2;
buttonRemovePlane.Text = "Удалить самолет";
buttonRemovePlane.UseVisualStyleBackColor = true;
buttonRemovePlane.Click += buttonRemovePlane_Click;
//
// buttonAddPlane
//
buttonAddPlane.Location = new Point(6, 26);
buttonAddPlane.Name = "buttonAddPlane";
buttonAddPlane.Size = new Size(218, 29);
buttonAddPlane.TabIndex = 0;
buttonAddPlane.Text = "Добавить самолет";
buttonAddPlane.UseVisualStyleBackColor = true;
buttonAddPlane.Click += buttonAddPlane_Click;
//
// pictureBoxCollection
//
pictureBoxCollection.Dock = DockStyle.Fill;
pictureBoxCollection.Location = new Point(0, 0);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(787, 538);
pictureBoxCollection.TabIndex = 1;
pictureBoxCollection.TabStop = false;
//
// FormPlaneCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1017, 538);
Controls.Add(pictureBoxCollection);
Controls.Add(groupBoxTools);
Name = "FormPlaneCollection";
Text = "Набор самолетов";
groupBoxTools.ResumeLayout(false);
groupBoxTools.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
ResumeLayout(false);
}
#endregion
private GroupBox groupBoxTools;
private Button buttonRefreshCollection;
private Button buttonRemovePlane;
private Button buttonAddPlane;
private MaskedTextBox maskedTextBoxNumber;
private PictureBox pictureBoxCollection;
}
}

View File

@ -0,0 +1,83 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ProjectStormtrooper
{
/// <summary>
/// Форма для работы с набором объектов класса DrawningPlane
/// </summary>
public partial class FormPlaneCollection : Form
{
/// <summary>
/// Набор объектов
/// </summary>
private readonly PlanesGenericCollection<DrawingPlane, DrawingObjectPlane> _planes;
/// <summary>
/// Конструктор
/// </summary>
public FormPlaneCollection()
{
InitializeComponent();
_planes = new PlanesGenericCollection<DrawingPlane, DrawingObjectPlane>(pictureBoxCollection.Width, pictureBoxCollection.Height);
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAddPlane_Click(object sender, EventArgs e)
{
FormStormtrooper form = new();
if (form.ShowDialog() == DialogResult.OK)
{
if (_planes + form.SelectedPlane > -1)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = _planes.ShowPlanes();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
}
/// <summary>
/// Удаление объекта из набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonRemovePlane_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (_planes - pos != null)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = _planes.ShowPlanes();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
/// <summary>
/// Обновление рисунка по набору
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonRefreshCollection_Click(object sender, EventArgs e)
{
pictureBoxCollection.Image = _planes.ShowPlanes();
}
}
}

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 @@
buttonCreatePlane = new Button();
comboBoxStrategy = new ComboBox();
buttonStep = new Button();
buttonSelectPlane = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxStormtrooper).BeginInit();
SuspendLayout();
//
@ -45,7 +46,7 @@
pictureBoxStormtrooper.Dock = DockStyle.Fill;
pictureBoxStormtrooper.Location = new Point(0, 0);
pictureBoxStormtrooper.Name = "pictureBoxStormtrooper";
pictureBoxStormtrooper.Size = new Size(882, 453);
pictureBoxStormtrooper.Size = new Size(948, 546);
pictureBoxStormtrooper.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBoxStormtrooper.TabIndex = 0;
pictureBoxStormtrooper.TabStop = false;
@ -53,7 +54,7 @@
// buttonCreateStormtrooper
//
buttonCreateStormtrooper.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateStormtrooper.Location = new Point(12, 412);
buttonCreateStormtrooper.Location = new Point(12, 505);
buttonCreateStormtrooper.Name = "buttonCreateStormtrooper";
buttonCreateStormtrooper.Size = new Size(201, 29);
buttonCreateStormtrooper.TabIndex = 1;
@ -66,7 +67,7 @@
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = Properties.Resources.arrowUP;
buttonUp.BackgroundImageLayout = ImageLayout.Zoom;
buttonUp.Location = new Point(804, 375);
buttonUp.Location = new Point(870, 468);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(30, 30);
buttonUp.TabIndex = 2;
@ -78,7 +79,7 @@
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = Properties.Resources.arrowDOWN;
buttonDown.BackgroundImageLayout = ImageLayout.Zoom;
buttonDown.Location = new Point(804, 411);
buttonDown.Location = new Point(870, 504);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(30, 30);
buttonDown.TabIndex = 3;
@ -90,7 +91,7 @@
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = Properties.Resources.arrowLEFT;
buttonLeft.BackgroundImageLayout = ImageLayout.Zoom;
buttonLeft.Location = new Point(768, 411);
buttonLeft.Location = new Point(834, 504);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(30, 30);
buttonLeft.TabIndex = 4;
@ -102,7 +103,7 @@
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = Properties.Resources.arrowRIGHT;
buttonRight.BackgroundImageLayout = ImageLayout.Zoom;
buttonRight.Location = new Point(840, 411);
buttonRight.Location = new Point(906, 504);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(30, 30);
buttonRight.TabIndex = 5;
@ -112,7 +113,7 @@
// buttonCreatePlane
//
buttonCreatePlane.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreatePlane.Location = new Point(219, 412);
buttonCreatePlane.Location = new Point(219, 505);
buttonCreatePlane.Name = "buttonCreatePlane";
buttonCreatePlane.Size = new Size(201, 29);
buttonCreatePlane.TabIndex = 6;
@ -122,17 +123,19 @@
//
// comboBoxStrategy
//
comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right;
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "MoveToCenter", "MoveToRightBottom" });
comboBoxStrategy.Location = new Point(719, 12);
comboBoxStrategy.Location = new Point(785, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(151, 28);
comboBoxStrategy.TabIndex = 7;
//
// buttonStep
//
buttonStep.Location = new Point(776, 46);
buttonStep.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonStep.Location = new Point(842, 46);
buttonStep.Name = "buttonStep";
buttonStep.Size = new Size(94, 29);
buttonStep.TabIndex = 8;
@ -140,11 +143,22 @@
buttonStep.UseVisualStyleBackColor = true;
buttonStep.Click += buttonStep_Click;
//
// buttonSelectPlane
//
buttonSelectPlane.Location = new Point(426, 505);
buttonSelectPlane.Name = "buttonSelectPlane";
buttonSelectPlane.Size = new Size(137, 29);
buttonSelectPlane.TabIndex = 9;
buttonSelectPlane.Text = "Выбрать";
buttonSelectPlane.UseVisualStyleBackColor = true;
buttonSelectPlane.Click += ButtonSelectPlane_Click;
//
// FormStormtrooper
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(882, 453);
ClientSize = new Size(948, 546);
Controls.Add(buttonSelectPlane);
Controls.Add(buttonStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreatePlane);
@ -173,5 +187,6 @@
private Button buttonCreatePlane;
private ComboBox comboBoxStrategy;
private Button buttonStep;
private Button buttonSelectPlane;
}
}

View File

@ -9,13 +9,22 @@ namespace ProjectStormtrooper
/// Ïîëå-îáúåêò äëÿ ïðîðèñîâêè îáúåêòà
/// </summary>
private DrawingPlane? _drawingPlane;
private AbstractStrategy? _abstractStrategy;
/// <summary>
/// Ńňđŕňĺăč˙ ďĺđĺěĺůĺíč˙
/// </summary>
private AbstractStrategy? _strategy;
/// <summary>
/// Âűáđŕííűé ŕâňîěîáčëü
/// </summary>
public DrawingPlane? SelectedPlane { get; private set; }
/// <summary>
/// Èíèöèàëèçàöèÿ ôîðìû
/// </summary>
public FormStormtrooper()
{
InitializeComponent();
_strategy = null;
SelectedPlane = null;
}
/// <summary>
/// Ìåòîä ïðîðèñîâêè îáúåêòà
@ -39,11 +48,23 @@ namespace ProjectStormtrooper
private void buttonCreateStormtrooper_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));
dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
dopColor = dialog.Color;
}
_drawingPlane = new DrawingStormtrooper(
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)),
pictureBoxStormtrooper.Width,
@ -60,10 +81,16 @@ namespace ProjectStormtrooper
private void buttonCreatePlane_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;
}
_drawingPlane = new DrawingPlane(
random.Next(100, 300),
random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
color,
pictureBoxStormtrooper.Width,
pictureBoxStormtrooper.Height
);
@ -112,30 +139,40 @@ namespace ProjectStormtrooper
}
if (comboBoxStrategy.Enabled)
{
_abstractStrategy = comboBoxStrategy.SelectedIndex switch
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToRightBottom(),
_ => null,
};
if (_abstractStrategy == null)
if (_strategy == null)
{
return;
}
_abstractStrategy.SetData(new DrawingObjectPlane(_drawingPlane), pictureBoxStormtrooper.Width, pictureBoxStormtrooper.Height);
comboBoxStrategy.Enabled = false;
_strategy.SetData(new DrawingObjectPlane(_drawingPlane), pictureBoxStormtrooper.Width, pictureBoxStormtrooper.Height);
}
if (_abstractStrategy == null)
if (_strategy == null)
{
return;
}
_abstractStrategy.MakeStep();
comboBoxStrategy.Enabled = false;
_strategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
if (_strategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_abstractStrategy = null;
_strategy = null;
}
}
/// <summary>
/// Âűáîđ ńŕěîëĺňŕ
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSelectPlane_Click(object sender, EventArgs e)
{
SelectedPlane = _drawingPlane;
DialogResult = DialogResult.OK;
}
}
}

View File

@ -0,0 +1,134 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectStormtrooper
{
/// <summary>
/// Параметризованный класс для набора объектов DrawningPlane
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
internal class PlanesGenericCollection<T, U>
where T : DrawingPlane
where U : IMoveableObject
{
/// <summary>
/// Ширина окна прорисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна прорисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Размер занимаемого объектом места (ширина)
/// </summary>
private readonly int _placeSizeWidth = 160;
/// <summary>
/// Размер занимаемого объектом места (высота)
/// </summary>
private readonly int _placeSizeHeight = 120;
/// <summary>
/// Набор объектов
/// </summary>
private readonly SetGeneric<T> _collection;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
public PlanesGenericCollection(int picWidth, int picHeight)
{
int horizontalObjectsCount = picWidth / _placeSizeWidth;
int verticalObjectsCount = picHeight / _placeSizeHeight;
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = new SetGeneric<T>(horizontalObjectsCount * verticalObjectsCount);
}
/// <summary>
/// Перегрузка оператора сложения
/// </summary>
/// <param name="collect"></param>
/// <param name="obj"></param>
/// <returns></returns>
public static int operator +(PlanesGenericCollection<T, U> collect, T? obj)
{
if (obj == null)
{
return -1;
}
return collect?._collection.Insert(obj) ?? -1;
}
/// <summary>
/// Перегрузка оператора вычитания
/// </summary>
/// <param name="collect"></param>
/// <param name="pos"></param>
/// <returns></returns>
public static T? operator -(PlanesGenericCollection<T, U> collect, int pos)
Review

Требовалось поменять тип возвращаемого значения

Требовалось поменять тип возвращаемого значения
{
return collect._collection.Remove(pos);
}
/// <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 ShowPlanes()
{
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>
/// <param name="g"></param>
private void DrawObjects(Graphics g)
{
int placesColumnCount = _pictureHeight / _placeSizeHeight;
int placesRowCount = _pictureWidth / _placeSizeWidth;
for (int i = 0; i < _collection.Count; i++)
{
// получение объекта
var obj = _collection.Get(i);
// установка позиции
obj?.SetPosition(
(int)((placesRowCount - 1) * _placeSizeWidth - (i % placesColumnCount * _placeSizeWidth) + (_placeSizeWidth - obj?.GetWidth) / 2),
(int)(i / placesColumnCount * _placeSizeHeight + (_placeSizeHeight - obj?.GetHeight) / 2)
);
// прорисовка объекта
obj?.DrawTransport(g);
}
}
}
}

View File

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

View File

@ -0,0 +1,114 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectStormtrooper
{
/// <summary>
/// Параметризованный набор объектов
/// </summary>
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="plane"></param>
/// <returns></returns>
public int Insert(T plane)
{
return Insert(plane, 0);
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="plane"></param>
/// <param name="position"></param>
/// <returns></returns>
public int Insert(T plane, int position)
{
// Проверка позиции
if (position < 0 || position >= Count)
{
return -1;
}
// Проверка, что элемент массива по этой позиции пустой
if (_places[position] != null)
{
// Проверка, что после вставляемого элемента в массиве есть пустой элемент
int nullIndex = -1;
for (int i = position + 1; i < Count; i++)
{
if (_places[i] == null)
{
nullIndex = i;
break;
}
}
// Если пустого элемента нет, то выходим
if (nullIndex < 0)
{
return -1;
}
// Сдвиг всех объектов, находящихся справа от позиции до первого пустого элемента
int j = nullIndex - 1;
while (j >= position)
{
_places[j + 1] = _places[j];
j--;
}
}
// Вставка по позиции
_places[position] = plane;
return position;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T? Remove(int position)
{
// Проверка позиции
if (position < 0 || position >= Count)
{
return null;
}
// Удаление объекта из массива, присвоив элементу массива значение null
T? plane = _places[position];
_places[position] = null;
return plane;
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T? Get(int position)
{
// Проверка позиции
if (position < 0 || position >= Count)
{
return null;
}
return _places[position];
}
}
}