14 Commits

Author SHA1 Message Date
37aee9ad6a Фикс бага с цветами 2023-11-20 21:37:49 +04:00
b46a5f46b0 Переписал загрузку на StreamReader 2023-11-20 18:45:39 +04:00
ca9860ba86 Переписал сохранение на StreamWriter 2023-11-20 18:36:37 +04:00
262ac5cd8c Работает сохранение и загрузка 2023-11-20 18:23:43 +04:00
c9f8764af0 Добавлены методы сохранения и загрузки информации из файла 2023-11-20 17:53:29 +04:00
87c5a98333 Добавлен класс расширение ExtensionDrawingPlane 2023-11-20 17:36:21 +04:00
cd74aa1932 Фиксы по лабе и требованиям 2023-11-06 14:44:39 +04:00
5a616231fd Изменена логика добавления обхекта в классе FormPlaneCollection 2023-11-06 13:36:28 +04:00
0b208db4dd Добавлена форма FormPlaneConfig и реализована его логика 2023-11-06 13:31:26 +04:00
51a27f8e12 Доработана форма 2023-10-22 15:36:49 +04:00
bdc1823059 Добавлен класс PlanesGenericStorage 2023-10-22 15:20:44 +04:00
2a452af6b5 Внесены правки в PlanesGenericCollection 2023-10-22 15:11:20 +04:00
89c04361e4 Правлен класс SetGeneric 2023-10-22 15:05:34 +04:00
3194d59c46 Внесены правки в SetGeneric 2023-10-22 15:03:36 +04:00
13 changed files with 1176 additions and 75 deletions

View File

@@ -18,11 +18,11 @@ namespace ProjectStormtrooper
/// <summary>
/// Ширина окна
/// </summary>
private int _pictureWidth;
public int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int _pictureHeight;
public int _pictureHeight;
/// <summary>
/// Левая координата начала прорисовки
/// </summary>

View File

@@ -41,5 +41,9 @@ namespace ProjectStormtrooper
Weight = weight;
BodyColor = bodyColor;
}
public void SetColor(Color color)
{
BodyColor = color;
}
}
}

View File

@@ -28,5 +28,9 @@ namespace ProjectStormtrooper
Rockets = rockets;
Bombs = bombs;
}
public void SetAdditionalColor(Color color)
{
AdditionalColor = color;
}
}
}

View File

@@ -0,0 +1,53 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectStormtrooper
{
public static class ExtensionDrawingPlane
{
/// <summary>
/// Создание объекта из строки
/// </summary>
public static DrawingPlane? CreateDrawingPlane(this string info, char separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawingPlane(Convert.ToInt32(strs[0]), Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
}
if (strs.Length == 6)
{
return new DrawingStormtrooper(
Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]),
Color.FromName(strs[2]),
Color.FromName(strs[3]),
Convert.ToBoolean(strs[4]),
Convert.ToBoolean(strs[5]),
width,
height);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
public static string GetDataForSave(this DrawingPlane drawningPlane, char separatorForObject)
{
var plane = drawningPlane.EntityPlane;
if (plane == null)
{
return string.Empty;
}
var str = $"{plane.Speed}{separatorForObject}{plane.Weight}{separatorForObject}{plane.BodyColor.Name}";
if (plane is not EntityStormtrooper stormtrooper)
{
return str;
}
return $"{str}{separatorForObject}{stormtrooper.AdditionalColor.Name}{separatorForObject}{stormtrooper.Rockets}{separatorForObject}{stormtrooper.Bombs}";
}
}
}

View File

@@ -29,32 +29,96 @@
private void InitializeComponent()
{
groupBoxTools = new GroupBox();
groupBoxStorages = new GroupBox();
buttonRemoveStorage = new Button();
listBoxStorages = new ListBox();
buttonAddStorage = new Button();
textBoxStorageName = new TextBox();
maskedTextBoxNumber = new MaskedTextBox();
buttonRefreshCollection = new Button();
buttonRemovePlane = new Button();
buttonAddPlane = new Button();
pictureBoxCollection = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
сохранитьToolStripMenuItem = new ToolStripMenuItem();
загрузитьToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
groupBoxTools.SuspendLayout();
groupBoxStorages.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// groupBoxTools
//
groupBoxTools.Controls.Add(groupBoxStorages);
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.Location = new Point(787, 28);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(230, 538);
groupBoxTools.Size = new Size(230, 510);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// groupBoxStorages
//
groupBoxStorages.Controls.Add(buttonRemoveStorage);
groupBoxStorages.Controls.Add(listBoxStorages);
groupBoxStorages.Controls.Add(buttonAddStorage);
groupBoxStorages.Controls.Add(textBoxStorageName);
groupBoxStorages.Location = new Point(6, 26);
groupBoxStorages.Name = "groupBoxStorages";
groupBoxStorages.Size = new Size(218, 241);
groupBoxStorages.TabIndex = 5;
groupBoxStorages.TabStop = false;
groupBoxStorages.Text = "Наборы";
//
// buttonRemoveStorage
//
buttonRemoveStorage.Location = new Point(6, 204);
buttonRemoveStorage.Name = "buttonRemoveStorage";
buttonRemoveStorage.Size = new Size(206, 29);
buttonRemoveStorage.TabIndex = 3;
buttonRemoveStorage.Text = "Удалить набор";
buttonRemoveStorage.UseVisualStyleBackColor = true;
buttonRemoveStorage.Click += buttonDelStorage_Click;
//
// listBoxStorages
//
listBoxStorages.FormattingEnabled = true;
listBoxStorages.ItemHeight = 20;
listBoxStorages.Location = new Point(6, 94);
listBoxStorages.Name = "listBoxStorages";
listBoxStorages.Size = new Size(206, 104);
listBoxStorages.TabIndex = 2;
listBoxStorages.SelectedIndexChanged += listBoxStorages_SelectedIndexChanged;
//
// buttonAddStorage
//
buttonAddStorage.Location = new Point(6, 59);
buttonAddStorage.Name = "buttonAddStorage";
buttonAddStorage.Size = new Size(206, 29);
buttonAddStorage.TabIndex = 1;
buttonAddStorage.Text = "Добавить набор";
buttonAddStorage.UseVisualStyleBackColor = true;
buttonAddStorage.Click += buttonAddStorage_Click;
//
// textBoxStorageName
//
textBoxStorageName.Location = new Point(6, 26);
textBoxStorageName.Name = "textBoxStorageName";
textBoxStorageName.Size = new Size(206, 27);
textBoxStorageName.TabIndex = 0;
//
// maskedTextBoxNumber
//
maskedTextBoxNumber.Location = new Point(6, 87);
maskedTextBoxNumber.Location = new Point(6, 404);
maskedTextBoxNumber.Mask = "00";
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(218, 27);
@@ -64,7 +128,7 @@
//
// buttonRefreshCollection
//
buttonRefreshCollection.Location = new Point(6, 180);
buttonRefreshCollection.Location = new Point(6, 497);
buttonRefreshCollection.Name = "buttonRefreshCollection";
buttonRefreshCollection.Size = new Size(218, 29);
buttonRefreshCollection.TabIndex = 3;
@@ -74,7 +138,7 @@
//
// buttonRemovePlane
//
buttonRemovePlane.Location = new Point(6, 120);
buttonRemovePlane.Location = new Point(6, 437);
buttonRemovePlane.Name = "buttonRemovePlane";
buttonRemovePlane.Size = new Size(218, 29);
buttonRemovePlane.TabIndex = 2;
@@ -84,7 +148,7 @@
//
// buttonAddPlane
//
buttonAddPlane.Location = new Point(6, 26);
buttonAddPlane.Location = new Point(6, 349);
buttonAddPlane.Name = "buttonAddPlane";
buttonAddPlane.Size = new Size(218, 29);
buttonAddPlane.TabIndex = 0;
@@ -95,12 +159,52 @@
// pictureBoxCollection
//
pictureBoxCollection.Dock = DockStyle.Fill;
pictureBoxCollection.Location = new Point(0, 0);
pictureBoxCollection.Location = new Point(0, 28);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(787, 538);
pictureBoxCollection.Size = new Size(787, 510);
pictureBoxCollection.TabIndex = 1;
pictureBoxCollection.TabStop = false;
//
// menuStrip
//
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(1017, 28);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { сохранитьToolStripMenuItem, загрузитьToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(59, 24);
файлToolStripMenuItem.Text = "Файл";
//
// сохранитьToolStripMenuItem
//
сохранитьToolStripMenuItem.Name = "сохранитьToolStripMenuItem";
сохранитьToolStripMenuItem.Size = new Size(166, 26);
сохранитьToolStripMenuItem.Text = "Сохранить";
сохранитьToolStripMenuItem.Click += saveToFileToolStripMenuItem_Click;
//
// загрузитьToolStripMenuItem
//
загрузитьToolStripMenuItem.Name = агрузитьToolStripMenuItem";
загрузитьToolStripMenuItem.Size = new Size(166, 26);
загрузитьToolStripMenuItem.Text = "Загрузить";
загрузитьToolStripMenuItem.Click += loadFromFileToolStripMenuItem_Click;
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog1";
openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// FormPlaneCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
@@ -108,12 +212,19 @@
ClientSize = new Size(1017, 538);
Controls.Add(pictureBoxCollection);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormPlaneCollection";
Text = "Набор самолетов";
groupBoxTools.ResumeLayout(false);
groupBoxTools.PerformLayout();
groupBoxStorages.ResumeLayout(false);
groupBoxStorages.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
@@ -124,5 +235,16 @@
private Button buttonAddPlane;
private MaskedTextBox maskedTextBoxNumber;
private PictureBox pictureBoxCollection;
private GroupBox groupBoxStorages;
private Button buttonRemoveStorage;
private ListBox listBoxStorages;
private Button buttonAddStorage;
private TextBox textBoxStorageName;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem сохранитьToolStripMenuItem;
private ToolStripMenuItem загрузитьToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
}
}

View File

@@ -18,14 +18,75 @@ namespace ProjectStormtrooper
/// <summary>
/// Набор объектов
/// </summary>
private readonly PlanesGenericCollection<DrawingPlane, DrawingObjectPlane> _planes;
private readonly PlanesGenericStorage _storage;
/// <summary>
/// Конструктор
/// </summary>
public FormPlaneCollection()
{
InitializeComponent();
_planes = new PlanesGenericCollection<DrawingPlane, DrawingObjectPlane>(pictureBoxCollection.Width, pictureBoxCollection.Height);
_storage = new PlanesGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
}
/// <summary>
/// Заполнение listBoxObjects
/// </summary>
private void ReloadObjects()
{
int index = listBoxStorages.SelectedIndex;
listBoxStorages.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++)
{
listBoxStorages.Items.Add(_storage.Keys[i]);
}
if (listBoxStorages.Items.Count > 0 && (index == -1 || index >= listBoxStorages.Items.Count))
{
listBoxStorages.SelectedIndex = 0;
}
else if (listBoxStorages.Items.Count > 0 && index > -1 && index < listBoxStorages.Items.Count)
{
listBoxStorages.SelectedIndex = index;
}
}
/// <summary>
/// Добавление набора в коллекцию
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAddStorage_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxStorageName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
}
/// <summary>
/// Выбор набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void listBoxStorages_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBoxCollection.Image = _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowPlanes();
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonDelStorage_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty);
ReloadObjects();
}
}
/// <summary>
/// Добавление объекта в набор
@@ -34,18 +95,31 @@ namespace ProjectStormtrooper
/// <param name="e"></param>
private void buttonAddPlane_Click(object sender, EventArgs e)
{
FormStormtrooper form = new();
if (form.ShowDialog() == DialogResult.OK)
var formPlaneConfig = new FormPlaneConfig();
formPlaneConfig.AddEvent(AddPlaneListener);
formPlaneConfig.Show();
}
public void AddPlaneListener(DrawingPlane plane)
{
plane._pictureWidth = pictureBoxCollection.Width;
plane._pictureHeight = pictureBoxCollection.Height;
if (listBoxStorages.SelectedIndex == -1)
{
if (_planes + form.SelectedPlane > -1)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = _planes.ShowPlanes();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
if (obj + plane > -1)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowPlanes();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
/// <summary>
@@ -55,15 +129,24 @@ namespace ProjectStormtrooper
/// <param name="e"></param>
private void buttonRemovePlane_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (_planes - pos != null)
if (obj - pos != null)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = _planes.ShowPlanes();
pictureBoxCollection.Image = obj.ShowPlanes();
}
else
{
@@ -77,7 +160,52 @@ namespace ProjectStormtrooper
/// <param name="e"></param>
private void buttonRefreshCollection_Click(object sender, EventArgs e)
{
pictureBoxCollection.Image = _planes.ShowPlanes();
RefreshCollection();
}
private void RefreshCollection()
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
pictureBoxCollection.Image = obj.ShowPlanes();
}
private void saveToFileToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.SaveData(saveFileDialog.FileName))
{
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void loadFromFileToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.LoadData(openFileDialog.FileName))
{
ReloadObjects();
RefreshCollection();
MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}

View File

@@ -117,4 +117,13 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>152, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>319, 17</value>
</metadata>
</root>

View File

@@ -0,0 +1,358 @@
namespace ProjectStormtrooper
{
partial class FormPlaneConfig
{
/// <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()
{
groupBoxParams = new GroupBox();
groupBoxColors = new GroupBox();
panelColorPink = new Panel();
panelColorPurple = new Panel();
panelColorBlue = new Panel();
panelColorBrown = new Panel();
panelColorGreen = new Panel();
panelColorLightBlue = new Panel();
panelColorYellow = new Panel();
panelColorRed = new Panel();
labelStormtrooper = new Label();
labelPlane = new Label();
checkBoxRockets = new CheckBox();
checkBoxBombs = new CheckBox();
numericUpDownWeight = new NumericUpDown();
numericUpDownSpeed = new NumericUpDown();
labelWeight = new Label();
labelSpeed = new Label();
buttonCancel = new Button();
buttonApply = new Button();
pictureBoxObject = new PictureBox();
labelAddColor = new Label();
labelColor = new Label();
panelControl = new Panel();
groupBoxParams.SuspendLayout();
groupBoxColors.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
panelControl.SuspendLayout();
SuspendLayout();
//
// groupBoxParams
//
groupBoxParams.Controls.Add(groupBoxColors);
groupBoxParams.Controls.Add(labelStormtrooper);
groupBoxParams.Controls.Add(labelPlane);
groupBoxParams.Controls.Add(checkBoxRockets);
groupBoxParams.Controls.Add(checkBoxBombs);
groupBoxParams.Controls.Add(numericUpDownWeight);
groupBoxParams.Controls.Add(numericUpDownSpeed);
groupBoxParams.Controls.Add(labelWeight);
groupBoxParams.Controls.Add(labelSpeed);
groupBoxParams.Location = new Point(2, 7);
groupBoxParams.Name = "groupBoxParams";
groupBoxParams.Size = new Size(497, 261);
groupBoxParams.TabIndex = 0;
groupBoxParams.TabStop = false;
groupBoxParams.Text = "Параметры";
//
// groupBoxColors
//
groupBoxColors.Controls.Add(panelColorPink);
groupBoxColors.Controls.Add(panelColorPurple);
groupBoxColors.Controls.Add(panelColorBlue);
groupBoxColors.Controls.Add(panelColorBrown);
groupBoxColors.Controls.Add(panelColorGreen);
groupBoxColors.Controls.Add(panelColorLightBlue);
groupBoxColors.Controls.Add(panelColorYellow);
groupBoxColors.Controls.Add(panelColorRed);
groupBoxColors.Location = new Point(176, 26);
groupBoxColors.Name = "groupBoxColors";
groupBoxColors.Size = new Size(308, 156);
groupBoxColors.TabIndex = 8;
groupBoxColors.TabStop = false;
groupBoxColors.Text = "Цвета";
//
// panelColorPink
//
panelColorPink.BackColor = Color.PeachPuff;
panelColorPink.Location = new Point(241, 89);
panelColorPink.Name = "panelColorPink";
panelColorPink.Size = new Size(50, 50);
panelColorPink.TabIndex = 1;
//
// panelColorPurple
//
panelColorPurple.BackColor = Color.Fuchsia;
panelColorPurple.Location = new Point(164, 89);
panelColorPurple.Name = "panelColorPurple";
panelColorPurple.Size = new Size(50, 50);
panelColorPurple.TabIndex = 1;
//
// panelColorBlue
//
panelColorBlue.BackColor = Color.Blue;
panelColorBlue.Location = new Point(87, 89);
panelColorBlue.Name = "panelColorBlue";
panelColorBlue.Size = new Size(50, 50);
panelColorBlue.TabIndex = 1;
//
// panelColorBrown
//
panelColorBrown.BackColor = Color.DarkRed;
panelColorBrown.Location = new Point(17, 89);
panelColorBrown.Name = "panelColorBrown";
panelColorBrown.Size = new Size(50, 50);
panelColorBrown.TabIndex = 3;
//
// panelColorGreen
//
panelColorGreen.BackColor = Color.Lime;
panelColorGreen.Location = new Point(241, 26);
panelColorGreen.Name = "panelColorGreen";
panelColorGreen.Size = new Size(50, 50);
panelColorGreen.TabIndex = 1;
//
// panelColorLightBlue
//
panelColorLightBlue.BackColor = Color.Cyan;
panelColorLightBlue.Location = new Point(164, 26);
panelColorLightBlue.Name = "panelColorLightBlue";
panelColorLightBlue.Size = new Size(50, 50);
panelColorLightBlue.TabIndex = 2;
//
// panelColorYellow
//
panelColorYellow.BackColor = Color.Yellow;
panelColorYellow.Location = new Point(87, 26);
panelColorYellow.Name = "panelColorYellow";
panelColorYellow.Size = new Size(50, 50);
panelColorYellow.TabIndex = 1;
//
// panelColorRed
//
panelColorRed.BackColor = Color.Red;
panelColorRed.Location = new Point(17, 26);
panelColorRed.Name = "panelColorRed";
panelColorRed.Size = new Size(50, 50);
panelColorRed.TabIndex = 0;
//
// labelStormtrooper
//
labelStormtrooper.BorderStyle = BorderStyle.FixedSingle;
labelStormtrooper.Location = new Point(340, 203);
labelStormtrooper.Name = "labelStormtrooper";
labelStormtrooper.Padding = new Padding(10);
labelStormtrooper.Size = new Size(127, 42);
labelStormtrooper.TabIndex = 7;
labelStormtrooper.Text = "Продвинутый";
labelStormtrooper.TextAlign = ContentAlignment.MiddleCenter;
labelStormtrooper.MouseDown += labelObject_MouseDown;
//
// labelPlane
//
labelPlane.BorderStyle = BorderStyle.FixedSingle;
labelPlane.Location = new Point(193, 203);
labelPlane.Name = "labelPlane";
labelPlane.Padding = new Padding(10);
labelPlane.Size = new Size(120, 42);
labelPlane.TabIndex = 6;
labelPlane.Text = "Простой";
labelPlane.TextAlign = ContentAlignment.MiddleCenter;
labelPlane.MouseDown += labelObject_MouseDown;
//
// checkBoxRockets
//
checkBoxRockets.AutoSize = true;
checkBoxRockets.Location = new Point(6, 145);
checkBoxRockets.Name = "checkBoxRockets";
checkBoxRockets.Size = new Size(79, 24);
checkBoxRockets.TabIndex = 5;
checkBoxRockets.Text = "Ракеты";
checkBoxRockets.UseVisualStyleBackColor = true;
//
// checkBoxBombs
//
checkBoxBombs.AutoSize = true;
checkBoxBombs.Location = new Point(6, 115);
checkBoxBombs.Name = "checkBoxBombs";
checkBoxBombs.Size = new Size(80, 24);
checkBoxBombs.TabIndex = 4;
checkBoxBombs.Text = "Бомбы";
checkBoxBombs.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(88, 73);
numericUpDownWeight.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownWeight.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownWeight.Name = "numericUpDownWeight";
numericUpDownWeight.Size = new Size(82, 27);
numericUpDownWeight.TabIndex = 3;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(88, 29);
numericUpDownSpeed.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownSpeed.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownSpeed.Name = "numericUpDownSpeed";
numericUpDownSpeed.Size = new Size(82, 27);
numericUpDownSpeed.TabIndex = 2;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelWeight
//
labelWeight.AutoSize = true;
labelWeight.Location = new Point(6, 75);
labelWeight.Name = "labelWeight";
labelWeight.Size = new Size(36, 20);
labelWeight.TabIndex = 1;
labelWeight.Text = "Вес:";
//
// labelSpeed
//
labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(6, 31);
labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(76, 20);
labelSpeed.TabIndex = 0;
labelSpeed.Text = "Скорость:";
//
// buttonCancel
//
buttonCancel.Location = new Point(178, 220);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(94, 29);
buttonCancel.TabIndex = 4;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
//
// buttonApply
//
buttonApply.Location = new Point(21, 220);
buttonApply.Name = "buttonApply";
buttonApply.Size = new Size(94, 29);
buttonApply.TabIndex = 3;
buttonApply.Text = "Добавить";
buttonApply.UseVisualStyleBackColor = true;
buttonApply.Click += buttonApply_Click;
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(21, 68);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(251, 146);
pictureBoxObject.TabIndex = 2;
pictureBoxObject.TabStop = false;
//
// labelAddColor
//
labelAddColor.AllowDrop = true;
labelAddColor.BorderStyle = BorderStyle.FixedSingle;
labelAddColor.Location = new Point(172, 16);
labelAddColor.Name = "labelAddColor";
labelAddColor.Size = new Size(100, 40);
labelAddColor.TabIndex = 1;
labelAddColor.Text = "Доп. цвет";
labelAddColor.TextAlign = ContentAlignment.MiddleCenter;
labelAddColor.DragDrop += labelAddColor_DragDrop;
labelAddColor.DragEnter += labelColor_DragEnter;
//
// labelColor
//
labelColor.AllowDrop = true;
labelColor.BorderStyle = BorderStyle.FixedSingle;
labelColor.Location = new Point(21, 16);
labelColor.Name = "labelColor";
labelColor.Size = new Size(100, 40);
labelColor.TabIndex = 0;
labelColor.Text = "Цвет";
labelColor.TextAlign = ContentAlignment.MiddleCenter;
labelColor.DragDrop += labelColor_DragDrop;
labelColor.DragEnter += labelColor_DragEnter;
//
// panelControl
//
panelControl.AllowDrop = true;
panelControl.Controls.Add(labelColor);
panelControl.Controls.Add(buttonCancel);
panelControl.Controls.Add(buttonApply);
panelControl.Controls.Add(pictureBoxObject);
panelControl.Controls.Add(labelAddColor);
panelControl.Location = new Point(505, 12);
panelControl.Name = "panelControl";
panelControl.Size = new Size(298, 256);
panelControl.TabIndex = 5;
panelControl.DragDrop += panelControlObject_DragDrop;
panelControl.DragEnter += panelControlObject_DragEnter;
//
// FormPlaneConfig
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(809, 275);
Controls.Add(panelControl);
Controls.Add(groupBoxParams);
Name = "FormPlaneConfig";
Text = "Создание объекта";
groupBoxParams.ResumeLayout(false);
groupBoxParams.PerformLayout();
groupBoxColors.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).EndInit();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).EndInit();
panelControl.ResumeLayout(false);
ResumeLayout(false);
}
#endregion
private GroupBox groupBoxParams;
private GroupBox groupBoxColors;
private Label labelStormtrooper;
private Label labelPlane;
private CheckBox checkBoxRockets;
private CheckBox checkBoxBombs;
private NumericUpDown numericUpDownWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelWeight;
private Label labelSpeed;
private Panel panelColorRed;
private Panel panelColorPink;
private Panel panelColorPurple;
private Panel panelColorBlue;
private Panel panelColorBrown;
private Panel panelColorGreen;
private Panel panelColorLightBlue;
private Panel panelColorYellow;
private Button buttonCancel;
private Button buttonApply;
private PictureBox pictureBoxObject;
private Label labelAddColor;
private Label labelColor;
private Panel panelControl;
}
}

View File

@@ -0,0 +1,127 @@
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
{
public partial class FormPlaneConfig : Form
{
/// <summary>
/// Переменная-выбранный самолет
/// </summary>
DrawingPlane? _plane = null;
/// <summary>
/// Событие
/// </summary>
private event Action<DrawingPlane>? EventAddPlane;
public FormPlaneConfig()
{
InitializeComponent();
panelColorRed.MouseDown += panelColor_MouseDown;
panelColorYellow.MouseDown += panelColor_MouseDown;
panelColorLightBlue.MouseDown += panelColor_MouseDown;
panelColorGreen.MouseDown += panelColor_MouseDown;
panelColorBrown.MouseDown += panelColor_MouseDown;
panelColorBlue.MouseDown += panelColor_MouseDown;
panelColorPurple.MouseDown += panelColor_MouseDown;
panelColorPink.MouseDown += panelColor_MouseDown;
buttonCancel.Click += (sender, e) => Close();
}
/// <summary>
/// Добавление события
/// </summary>
/// <param name="ev">Привязанный метод</param>
public void AddEvent(Action<DrawingPlane> ev)
{
if (EventAddPlane == null)
{
EventAddPlane = ev;
}
else
{
EventAddPlane += ev;
}
}
/// <summary>
/// Отрисовать машину
/// </summary>
private void DrawPlane()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_plane?.SetPosition((int)((pictureBoxObject.Width - _plane?.GetWidth) / 2), (int)((pictureBoxObject.Height - _plane?.GetHeight) / 2));
_plane?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
private void buttonApply_Click(object sender, EventArgs e)
{
EventAddPlane?.Invoke(_plane);
Close();
}
private void panelControlObject_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(DataFormats.Text) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void panelControlObject_DragDrop(object sender, DragEventArgs e)
{
switch (e.Data?.GetData(DataFormats.Text).ToString())
{
case "labelPlane":
_plane = new DrawingPlane((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value, Color.White, pictureBoxObject.Width, pictureBoxObject.Height);
break;
case "labelStormtrooper":
_plane = new DrawingStormtrooper((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value, Color.White, Color.Black, checkBoxRockets.Checked, checkBoxBombs.Checked, pictureBoxObject.Width, pictureBoxObject.Height);
break;
}
DrawPlane();
}
private void labelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label)?.DoDragDrop((sender as Label)?.Name, DragDropEffects.Move | DragDropEffects.Copy);
}
private void panelColor_MouseDown(object sender, MouseEventArgs e)
{
(sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor, DragDropEffects.Move | DragDropEffects.Copy);
}
private void labelColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(typeof(Color)) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void labelColor_DragDrop(object sender, DragEventArgs e)
{
if (_plane == null)
return;
_plane.EntityPlane.SetColor((Color)e.Data.GetData(typeof(Color).ToString()));
DrawPlane();
}
private void labelAddColor_DragDrop(object sender, DragEventArgs e)
{
if (_plane == null || _plane is not DrawingStormtrooper)
return;
(_plane.EntityPlane as EntityStormtrooper).SetAdditionalColor((Color)e.Data.GetData(typeof(Color).ToString()));
DrawPlane();
}
}
}

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

@@ -70,7 +70,12 @@ namespace ProjectStormtrooper
/// <returns></returns>
public static T? operator -(PlanesGenericCollection<T, U> collect, int pos)
{
return collect._collection.Remove(pos);
T? obj = collect._collection[pos];
if (obj != null)
{
collect._collection.Remove(pos);
}
return obj;
}
/// <summary>
/// Получение объекта IMoveableObject
@@ -79,7 +84,7 @@ namespace ProjectStormtrooper
/// <returns></returns>
public U? GetU(int pos)
{
return (U?)_collection.Get(pos)?.GetMoveableObject;
return (U?)_collection[pos]?.GetMoveableObject;
}
/// <summary>
/// Вывод всего набора объектов
@@ -117,18 +122,25 @@ namespace ProjectStormtrooper
{
int placesColumnCount = _pictureHeight / _placeSizeHeight;
int placesRowCount = _pictureWidth / _placeSizeWidth;
for (int i = 0; i < _collection.Count; i++)
int i = 0;
foreach (var plane in _collection.GetPlanes())
{
// получение объекта
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);
if (plane != null)
{
// установка позиции
plane.SetPosition(
(int)((placesRowCount - 1) * _placeSizeWidth - (i % placesColumnCount * _placeSizeWidth) + (_placeSizeWidth - plane.GetWidth) / 2),
(int)(i / placesColumnCount * _placeSizeHeight + (_placeSizeHeight - plane.GetHeight) / 2)
);
// прорисовка объекта
plane.DrawTransport(g);
}
i++;
}
}
/// <summary>
/// Получение объектов коллекции
/// </summary>
public IEnumerable<T?> GetPlanes => _collection.GetPlanes();
}
}

View File

@@ -0,0 +1,156 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectStormtrooper
{
internal class PlanesGenericStorage
{
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private static readonly char _separatorForKeyValue = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char _separatorRecords = ';';
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<string, PlanesGenericCollection<DrawingPlane, DrawingObjectPlane>> _planeStorages;
/// <summary>
/// Возвращение списка названий наборов
/// </summary>
public List<string> Keys => _planeStorages.Keys.ToList();
/// <summary>
/// Ширина окна отрисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна отрисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="pictureWidth"></param>
/// <param name="pictureHeight"></param>
public PlanesGenericStorage(int pictureWidth, int pictureHeight)
{
_planeStorages = new Dictionary<string, PlanesGenericCollection<DrawingPlane, DrawingObjectPlane>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
/// <summary>
/// Добавление набора
/// </summary>
/// <param name="name">Название набора</param>
public void AddSet(string name)
{
_planeStorages.Add(name, new PlanesGenericCollection<DrawingPlane, DrawingObjectPlane>(_pictureWidth, _pictureHeight));
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="name">Название набора</param>
public void DelSet(string name)
{
if (_planeStorages.ContainsKey(name))
_planeStorages.Remove(name);
}
/// <summary>
/// Доступ к набору
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public PlanesGenericCollection<DrawingPlane, DrawingObjectPlane>? this[string ind]
{
get
{
if (_planeStorages.ContainsKey(ind))
return _planeStorages[ind];
return null;
}
}
/// <summary>
/// Сохранение информации в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter sw = File.CreateText(filename))
{
sw.WriteLine($"PlaneStorage");
string storageString;
foreach (var storage in _planeStorages)
{
storageString = "";
foreach (var plane in storage.Value.GetPlanes)
{
storageString += $"{plane?.GetDataForSave(_separatorForObject)}{_separatorRecords}";
}
sw.WriteLine($"{storage.Key}{_separatorForKeyValue}{storageString}");
}
}
return true;
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
}
using (StreamReader sr = new StreamReader(filename))
{
string? currentLine = sr.ReadLine();
if (currentLine == null || !currentLine.Contains("PlaneStorage"))
{
return false;
}
_planeStorages.Clear();
currentLine = sr.ReadLine();
while (currentLine != null)
{
string[] record = currentLine.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
continue;
}
PlanesGenericCollection<DrawingPlane, DrawingObjectPlane> collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawingPlane? plane = elem?.CreateDrawingPlane(_separatorForObject, _pictureWidth, _pictureHeight);
if (plane != null)
{
if (collection + plane == -1)
{
return false;
}
}
}
_planeStorages.Add(record[0], collection);
currentLine = sr.ReadLine();
}
return true;
}
}
}
}

View File

@@ -12,20 +12,25 @@ namespace ProjectStormtrooper
internal class SetGeneric<T> where T : class
{
/// <summary>
/// Массив объектов, которые храним
/// Список объектов, которые храним
/// </summary>
private readonly T?[] _places;
private readonly List<T?> _places;
/// <summary>
/// Количество объектов в массиве
/// </summary>
public int Count => _places.Length;
public int Count => _places.Count;
/// <summary>
/// Максимальное количество объектов в списке
/// </summary>
private readonly int _maxCount;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetGeneric(int count)
{
_places = new T?[count];
_maxCount = count;
_places = new List<T?>(count);
}
/// <summary>
/// Добавления объекта в набор
@@ -45,38 +50,12 @@ namespace ProjectStormtrooper
public int Insert(T plane, int position)
{
// Проверка позиции
if (position < 0 || position >= Count)
if (position < 0 || position >= _maxCount)
{
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;
_places.Insert(position, plane);
return position;
}
/// <summary>
@@ -101,14 +80,43 @@ namespace ProjectStormtrooper
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T? Get(int position)
public T? this[int position]
{
// Проверка позиции
if (position < 0 || position >= Count)
get
{
return null;
// Проверка позиции
if (position < 0 || position >= Count)
{
return null;
}
return _places[position];
}
set
{
// Проверка позиции
// Проверка свободных мест в списке
if (position < 0 || position >= _maxCount || Count == _maxCount)
{
return;
}
// Вставка в список по позиции
_places.Insert(position, value);
}
}
/// <summary>
/// Проход по списку
/// </summary>
/// <returns></returns>
public IEnumerable<T?> GetPlanes(int? maxPlanes = null)
{
for (int i = 0; i < _places.Count; ++i)
{
yield return _places[i];
if (maxPlanes.HasValue && i == maxPlanes.Value)
{
yield break;
}
}
return _places[position];
}
}
}