Петрушин Егор ПИбд-22 Лабораторная работа №3 "Самоходная артиллерийская установка" #8

Closed
Egor_Petrushin wants to merge 7 commits from PIbd-22_Petrushin_E.A._Lab3 into PIbd-22_Petrushin_E.A._Lab2
10 changed files with 723 additions and 77 deletions

View File

@ -5,6 +5,7 @@ using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SelfPropelledArtilleryUnit.Entities;
using SelfPropelledArtilleryUnit.MovementStrategy;
namespace SelfPropelledArtilleryUnit.DrawningObjects
{
@ -217,5 +218,9 @@ namespace SelfPropelledArtilleryUnit.DrawningObjects
_ => false,
};
}
/// <summary>
/// Получение объекта IMoveableObject из объекта DrawningCar
/// </summary>
public IMoveableObject GetMoveableObject => new DrawningObjectSPAU(this);
}
}

View File

@ -1,6 +1,6 @@
namespace SelfPropelledArtilleryUnit
{
partial class Form
partial class FormSPAU
{
/// <summary>
/// Required designer variable.
@ -29,14 +29,15 @@
private void InitializeComponent()
{
pictureBoxSPAU = new PictureBox();
buttonCreate = new Button();
buttonUp = new Button();
buttonDown = new Button();
buttonLeft = new Button();
buttonRight = new Button();
buttonCreateParent = new Button();
buttonStep = new Button();
comboBoxStrategy = new ComboBox();
ButtonCreateSPAU = new Button();
ButtonCreateSPAUchild = new Button();
ButtonSelectSPAU = new Button();
ButtonStartegyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxSPAU).BeginInit();
SuspendLayout();
//
@ -49,17 +50,6 @@
pictureBoxSPAU.TabIndex = 0;
pictureBoxSPAU.TabStop = false;
//
// buttonCreate
//
buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreate.Location = new Point(134, 412);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(301, 29);
buttonCreate.TabIndex = 1;
buttonCreate.Text = "Создать САУ с залповой установкой";
buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += buttonCreate_Click;
//
// buttonUp
//
buttonUp.BackgroundImage = Properties.Resources.upper_arrow;
@ -104,26 +94,6 @@
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += buttonMove_Click;
//
// buttonCreateParent
//
buttonCreateParent.Location = new Point(12, 409);
buttonCreateParent.Name = "buttonCreateParent";
buttonCreateParent.Size = new Size(116, 30);
buttonCreateParent.TabIndex = 6;
buttonCreateParent.Text = "Создать САУ";
buttonCreateParent.UseVisualStyleBackColor = true;
buttonCreateParent.Click += buttonCreateParent_Click;
//
// buttonStep
//
buttonStep.Location = new Point(794, 65);
buttonStep.Name = "buttonStep";
buttonStep.Size = new Size(76, 30);
buttonStep.TabIndex = 7;
buttonStep.Text = "Шаг";
buttonStep.UseVisualStyleBackColor = true;
buttonStep.Click += buttonStep_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
@ -134,19 +104,60 @@
comboBoxStrategy.Size = new Size(103, 28);
comboBoxStrategy.TabIndex = 8;
//
// ButtonCreateSPAU
//
ButtonCreateSPAU.Location = new Point(12, 403);
ButtonCreateSPAU.Name = "ButtonCreateSPAU";
ButtonCreateSPAU.Size = new Size(153, 36);
ButtonCreateSPAU.TabIndex = 11;
ButtonCreateSPAU.Text = "Создать обычный";
ButtonCreateSPAU.UseVisualStyleBackColor = true;
ButtonCreateSPAU.Click += ButtonCreateSPAU_Click;
//
// ButtonCreateSPAUchild
//
ButtonCreateSPAUchild.Location = new Point(189, 403);
ButtonCreateSPAUchild.Name = "ButtonCreateSPAUchild";
ButtonCreateSPAUchild.Size = new Size(153, 35);
ButtonCreateSPAUchild.TabIndex = 12;
ButtonCreateSPAUchild.Text = "Создать с ЗУ";
ButtonCreateSPAUchild.UseVisualStyleBackColor = true;
ButtonCreateSPAUchild.Click += ButtonCreateSPAUchild_Click;
//
// ButtonSelectSPAU
//
ButtonSelectSPAU.Location = new Point(759, 90);
ButtonSelectSPAU.Name = "ButtonSelectSPAU";
ButtonSelectSPAU.Size = new Size(111, 37);
ButtonSelectSPAU.TabIndex = 13;
ButtonSelectSPAU.Text = "Выбрать";
ButtonSelectSPAU.UseVisualStyleBackColor = true;
ButtonSelectSPAU.Click += ButtonSelectSPAU_Click;
//
// ButtonStartegyStep
//
ButtonStartegyStep.Location = new Point(767, 49);
ButtonStartegyStep.Name = "ButtonStartegyStep";
ButtonStartegyStep.Size = new Size(103, 26);
ButtonStartegyStep.TabIndex = 14;
ButtonStartegyStep.Text = "Шаг";
ButtonStartegyStep.UseVisualStyleBackColor = true;
ButtonStartegyStep.Click += ButtonStartegyStep_Click;
//
// Form
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(882, 453);
Controls.Add(ButtonStartegyStep);
Controls.Add(ButtonSelectSPAU);
Controls.Add(ButtonCreateSPAUchild);
Controls.Add(ButtonCreateSPAU);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonStep);
Controls.Add(buttonCreateParent);
Controls.Add(buttonRight);
Controls.Add(buttonLeft);
Controls.Add(buttonDown);
Controls.Add(buttonUp);
Controls.Add(buttonCreate);
Controls.Add(pictureBoxSPAU);
Name = "Form";
StartPosition = FormStartPosition.CenterParent;
@ -158,13 +169,14 @@
#endregion
private PictureBox pictureBoxSPAU;
private Button buttonCreate;
private Button buttonUp;
private Button buttonDown;
private Button buttonLeft;
private Button buttonRight;
private Button buttonCreateParent;
private Button buttonStep;
private ComboBox comboBoxStrategy;
private Button ButtonCreateSPAU;
private Button ButtonCreateSPAUchild;
private Button ButtonSelectSPAU;
private Button ButtonStartegyStep;
}
}

View File

@ -1,9 +1,10 @@
using SelfPropelledArtilleryUnit.DrawningObjects;
using SelfPropelledArtilleryUnit.MovementStrategy;
using System.Drawing;
namespace SelfPropelledArtilleryUnit
{
public partial class Form : System.Windows.Forms.Form
public partial class FormSPAU : System.Windows.Forms.Form
{
/// <summary>
/// Ïîëå-îáúåêò äëÿ ïðîðèñîâêè îáúåêòà
@ -13,14 +14,20 @@ namespace SelfPropelledArtilleryUnit
/// <summary>
/// Ñòðàòåãèÿ ïåðåìåùåíèÿ
/// </summary>
private AbstractStrategy? _abstractStrategy;
private AbstractStrategy? _strategy;
/// <summary>
/// Âűáđŕííűé ŕâňîěîáčëü
/// </summary>
public DrawningSPAU? SelectedSPAU { get; private set; }
/// <summary>
/// Èíèöèàëèçàöèÿ ôîðìû
/// </summary>
public Form()
public FormSPAU()
{
InitializeComponent();
_strategy = null;
SelectedSPAU = null;
}
/// <summary>
/// Ìåòîä ïðîðèñîâêè ìàøèíû
@ -42,32 +49,36 @@ namespace SelfPropelledArtilleryUnit
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreate_Click(object sender, EventArgs e)
private void ButtonCreateSPAUchild_Click(object sender, EventArgs e)
{
Random random = new();
Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
Color dopColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
ColorDialog dialogColor = new();
if (dialogColor.ShowDialog() == DialogResult.OK)
{
color = dialogColor.Color;
}
ColorDialog dialogDop = new();
if (dialogDop.ShowDialog() == DialogResult.OK)
{
dopColor = dialogDop.Color;
}
_drawningSPAU = new DrawningSPAUchild(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)), true,
random.Next(1000, 3000), color,
dopColor, true,
pictureBoxSPAU.Width, pictureBoxSPAU.Height);
_drawningSPAU.SetPosition(random.Next(10, 100),
random.Next(10, 100));
Draw();
}
private void buttonCreateParent_Click(object sender, EventArgs e)
{
Random random = new();
_drawningSPAU = new DrawningSPAU(random.Next(100, 300),
random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256),
random.Next(0, 256)),
pictureBoxSPAU.Width, pictureBoxSPAU.Height);
_drawningSPAU.SetPosition(random.Next(10, 100),
random.Next(10, 100));
_drawningSPAU.SetPosition(random.Next(10, 100), random.Next(10,
100));
Draw();
}
/// <summary>
/// Čçěĺíĺíčĺ đŕçěĺđîâ ôîđěű
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonMove_Click(object sender, EventArgs e)
{
if (_drawningSPAU == null)
@ -93,7 +104,28 @@ namespace SelfPropelledArtilleryUnit
Draw();
}
private void buttonStep_Click(object sender, EventArgs e)
private void ButtonCreateSPAU_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;
}
_drawningSPAU = new DrawningSPAU(random.Next(100, 300),
random.Next(1000, 3000), color,
pictureBoxSPAU.Width, pictureBoxSPAU.Height);
_drawningSPAU.SetPosition(random.Next(10, 100), random.Next(10,
100));
Draw();
}
/// <summary>
/// Řŕă ńňđŕňĺăčč ďĺđĺěĺůĺíč˙
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonStartegyStep_Click(object sender, EventArgs e)
{
if (_drawningSPAU == null)
{
@ -101,34 +133,44 @@ namespace SelfPropelledArtilleryUnit
}
if (comboBoxStrategy.Enabled)
{
_abstractStrategy = comboBoxStrategy.SelectedIndex
switch
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_abstractStrategy == null)
if (_strategy == null)
{
return;
}
_abstractStrategy.SetData(new
DrawningObjectSPAU(_drawningSPAU), pictureBoxSPAU.Width,
pictureBoxSPAU.Height);
comboBoxStrategy.Enabled = false;
_strategy.SetData(_drawningSPAU.GetMoveableObject,
pictureBoxSPAU.Width, pictureBoxSPAU.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 ButtonSelectSPAU_Click(object sender, EventArgs e)
{
SelectedSPAU = _drawningSPAU;
DialogResult = DialogResult.OK;
}
}
}

View File

@ -0,0 +1,109 @@
namespace SelfPropelledArtilleryUnit
{
partial class FormSPAUCollection
{
/// <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()
{
pictureBoxCollection = new PictureBox();
maskedTextBoxNumber = new MaskedTextBox();
ButtonAddSPAU = new Button();
ButtonRemoveSPAU = new Button();
ButtonRefreshCollection = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
SuspendLayout();
//
// pictureBoxCollection
//
pictureBoxCollection.Location = new Point(12, 12);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(680, 432);
pictureBoxCollection.TabIndex = 0;
pictureBoxCollection.TabStop = false;
//
// maskedTextBoxNumber
//
maskedTextBoxNumber.Location = new Point(729, 51);
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(143, 27);
maskedTextBoxNumber.TabIndex = 1;
//
// ButtonAddSPAU
//
ButtonAddSPAU.Location = new Point(748, 102);
ButtonAddSPAU.Name = "ButtonAddSPAU";
ButtonAddSPAU.Size = new Size(102, 33);
ButtonAddSPAU.TabIndex = 2;
ButtonAddSPAU.Text = "Добавить";
ButtonAddSPAU.UseVisualStyleBackColor = true;
ButtonAddSPAU.Click += ButtonAddSPAU_Click;
//
// ButtonRemoveSPAU
//
ButtonRemoveSPAU.Location = new Point(750, 141);
ButtonRemoveSPAU.Name = "ButtonRemoveSPAU";
ButtonRemoveSPAU.Size = new Size(100, 37);
ButtonRemoveSPAU.TabIndex = 3;
ButtonRemoveSPAU.Text = "Удалить";
ButtonRemoveSPAU.UseVisualStyleBackColor = true;
ButtonRemoveSPAU.Click += ButtonRemoveSPAU_Click;
//
// ButtonRefreshCollection
//
ButtonRefreshCollection.Location = new Point(750, 195);
ButtonRefreshCollection.Name = "ButtonRefreshCollection";
ButtonRefreshCollection.Size = new Size(100, 35);
ButtonRefreshCollection.TabIndex = 4;
ButtonRefreshCollection.Text = "Обновить";
ButtonRefreshCollection.UseVisualStyleBackColor = true;
ButtonRefreshCollection.Click += ButtonRefreshCollection_Click;
//
// FormSPAUCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(899, 456);
Controls.Add(ButtonRefreshCollection);
Controls.Add(ButtonRemoveSPAU);
Controls.Add(ButtonAddSPAU);
Controls.Add(maskedTextBoxNumber);
Controls.Add(pictureBoxCollection);
Name = "FormSPAUCollection";
Text = "FormSPAUCollection";
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private PictureBox pictureBoxCollection;
private MaskedTextBox maskedTextBoxNumber;
private Button ButtonAddSPAU;
private Button ButtonRemoveSPAU;
private Button ButtonRefreshCollection;
}
}

View File

@ -0,0 +1,99 @@
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;
using SelfPropelledArtilleryUnit.DrawningObjects;
using SelfPropelledArtilleryUnit.MovementStrategy;
using SelfPropelledArtilleryUnit.Generics;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace SelfPropelledArtilleryUnit
{
/// <summary>
/// Форма для работы с набором объектов класса DrawningSPAU
/// </summary>
public partial class FormSPAUCollection : Form
{
readonly int countPlaces = 11;
/// <summary>
/// Набор объектов
/// </summary>
private readonly SPAUGenericCollection<DrawningSPAU, DrawningObjectSPAU> _SPAUs;
/// <summary>
/// Конструктор
/// </summary>
public FormSPAUCollection()
{
InitializeComponent();
_SPAUs = new SPAUGenericCollection<DrawningSPAU, DrawningObjectSPAU>(pictureBoxCollection.Width, pictureBoxCollection.Height);
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddSPAU_Click(object sender, EventArgs e)
{
FormSPAU form = new();
if (form.ShowDialog() == DialogResult.OK)
{
int addedIndex = _SPAUs + form.SelectedSPAU;
if (addedIndex != -1 && addedIndex <= countPlaces)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = _SPAUs.ShowSPAUs();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
}
/// <summary>
/// Удаление объекта из набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveSPAU_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos;
try {
pos = Convert.ToInt32(maskedTextBoxNumber.Text);
}
catch {
MessageBox.Show("Не удалось удалить объект");
return;
}
if (_SPAUs - pos)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = _SPAUs.ShowSPAUs();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
/// <summary>
/// Обновление рисунка по набору
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
{
pictureBoxCollection.Image = _SPAUs.ShowSPAUs();
}
}
}

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

@ -9,7 +9,8 @@ namespace SelfPropelledArtilleryUnit
static void Main()
{
ApplicationConfiguration.Initialize();
Application.Run(new Form());
Application.Run(new FormSPAUCollection());
//Application.Run(new FormSPAU());
}
}
}

View File

@ -0,0 +1,151 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SelfPropelledArtilleryUnit.DrawningObjects;
using SelfPropelledArtilleryUnit.MovementStrategy;
namespace SelfPropelledArtilleryUnit.Generics
{
/// <summary>
/// Параметризованный класс для набора объектов DrawningCar
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
internal class SPAUGenericCollection<T, U>
where T : DrawningSPAU
where U : IMoveableObject
{
/// <summary>
/// Ширина окна прорисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна прорисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Размер занимаемого объектом места (ширина)
/// </summary>
private readonly int _placeSizeWidth = 210;
/// <summary>
/// Размер занимаемого объектом места (высота)
/// </summary>
private readonly int _placeSizeHeight = 90;
/// <summary>
/// Набор объектов
/// </summary>
private readonly SetGeneric<T> _collection;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
public SPAUGenericCollection(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 +(SPAUGenericCollection<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 -(SPAUGenericCollection<T, U> collect, int pos)
{
T? obj = collect._collection.Get(pos);
if (obj != null)
{
collect._collection.Remove(pos);
}
else
{
return false;
}
return true;
}
/// <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 ShowSPAUs()
{
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)
{
int j = 0;
int stringCount = 0;
DrawningSPAU current;
for (int i = 0; i < _collection.Count; i++)
{
current = _collection.Get(i);
current?.SetPosition(stringCount * 200, 280 - j * 100);
stringCount++;
if (stringCount >= 3)
{
j++;
stringCount = 0;
}
current?.DrawTransport(g);
}
}
}
}

View File

@ -0,0 +1,107 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SelfPropelledArtilleryUnit.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="spau">Добавляемый автомобиль</param>
/// <returns></returns>
public int Insert(T spau)
{
return Insert(spau, 0);
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="car">Добавляемый автомобиль</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public int Insert(T spau, int position)
{
if (position < 0 || spau == null)
{
return -1;
}
if (position >= Count)
{
return -1;
}
// Ищем первую пустую позицию начиная с указанной позиции
int positionNull = Array.FindIndex(_places, position, x => x == null);
if (positionNull == -1 && _places[Count - 1] != null)
{
// Если пустых позиций нет и последняя позиция в массиве занята
return -1;
}
else if (positionNull == -1)
{
// Если позиция для вставки пустая, а пустых позиций больше нет
positionNull = Count - 1;
}
// Сдвигаем элементы вправо, начиная с первой пустой позиции и заканчивая указанной позицией
for (int i = positionNull; i > position; i--)
{
_places[i] = _places[i - 1];
}
// Вставка по позиции
_places[position] = spau;
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];
}
}
}