PIBD-14_Lavrova_K.I._LabWork06.Simple #9

Closed
Kristik wants to merge 2 commits from LabWork06 into LabWork05
15 changed files with 589 additions and 96 deletions

View File

@ -39,7 +39,7 @@ public abstract class AbstractCompany
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.SetMaxCount = GetMaxCount;
_collection.MaxCount = GetMaxCount;
}
/// <summary>
/// Перегрузка оператора сложения для класса

View File

@ -16,7 +16,8 @@ public interface ICollectionGenericObjects<T>
/// <summary>
/// Установка максимального количества элементов
/// </summary>
int SetMaxCount { set; }
int MaxCount { get; set; }
/// <summary>
/// Добавление объекта в коллекцию
/// </summary>
@ -42,5 +43,17 @@ public interface ICollectionGenericObjects<T>
/// <param name="position">Позиция</param>
/// <returns>Объект</returns>
T? Get(int position);
/// <summary>
/// Получение типа коллекции
/// </summary>
CollectionType GetCollectionType { get; }
int SetMaxCount { get; set; }
/// <summary>
/// Получение объектов коллекции по одному
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
}

View File

@ -21,7 +21,27 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
/// </summary>
private int _maxCount;
public int Count => _collection.Count;
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } }
public int MaxCount
{
get
{
return Count;
}
set
{
if (value > 0)
{
_maxCount = value;
}
}
}
public CollectionType GetCollectionType => CollectionType.List;
public int SetMaxCount { set => throw new NotImplementedException(); }
int ICollectionGenericObjects<T>.SetMaxCount { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
/// <summary>
/// Конструктор
/// </summary>
@ -30,6 +50,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
_collection = new();
}
public T? Get(int position)
{
if (position >= 0 && position < _collection.Count)
@ -76,4 +97,11 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
_collection.RemoveAt(position);
return temp;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < Count; ++i)
{
yield return _collection[i];
}
}
}

View File

@ -15,7 +15,33 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
private T?[] _collection;
public int Count => _collection.Length;
public int SetMaxCount { set { if (value > 0) { _collection = new T?[value]; } } }
public int MaxCount
{
get
{
return _collection.Length;
}
set
{
if (value > 0)
{
if (_collection.Length > 0)
{
Array.Resize(ref _collection, value);
}
else
{
_collection = new T?[value];
}
}
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
public int SetMaxCount { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
/// <summary>
/// Конструктор
/// </summary>
@ -92,4 +118,11 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return temp;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)
{
yield return _collection[i];
}
}
}

View File

@ -1,4 +1,5 @@
using System;
using lab1.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -10,7 +11,7 @@ namespace lab1.CollectionGenericObjects;
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : class
where T : DrawningTrackedVehicle
{
/// <summary>
/// Словарь(хранилище) с коллекциями
@ -77,4 +78,131 @@ public class StorageCollection<T>
}
}
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <summary>
/// Сохранение информации по штурмовику в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
{
if (_storages.Count == 0)
{
return false;
}
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{
writer.Write(Environment.NewLine);
if (value.Value.Count == 0)
{
continue;
}
writer.Write(value.Key);
writer.Write(_separatorForKeyValue);
writer.Write(value.Value.GetCollectionType);
writer.Write(_separatorForKeyValue);
writer.Write(value.Value.MaxCount);
writer.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
writer.Write(data);
writer.Write(_separatorItems);
}
}
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 fs = File.OpenText(filename))
{
string str = fs.ReadLine();
if (str == null || str.Length == 0)
{
return false;
}
if (!str.StartsWith(_collectionKey))
{
return false;
}
_storages.Clear();
string strs = "";
while ((strs = fs.ReadLine()) != null)
{
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
{
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
return false;
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningEntityFighter() is T fighter)
{
if (collection.Insert(fighter) == -1)
{
return false;
}
}
}
_storages.Add(record[0], collection);
}
return true;
}
}
/// <summary>
/// Создание коллекции по типу
/// </summary>
/// <param name="collectionType"></param>
/// <returns></returns>
private static ICollectionGenericObjects<T>?
CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
}

View File

@ -34,6 +34,7 @@ public class DrawningTrackedVehicle
/// Верхняя координата прорисовки истребителя
/// </summary>
protected int? _startPosY;
private EntityTrackedVehicle fighter;
/// <summary>
/// Ширина прорисовки истребителя
@ -106,6 +107,11 @@ public class DrawningTrackedVehicle
}
public DrawningTrackedVehicle(EntityTrackedVehicle fighter)
{
this.fighter = fighter;
}
/// <summary>
/// Установка границ поля

View File

@ -0,0 +1,59 @@
using lab1.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace lab1.Drawnings;
public static class ExtentionDrawningTrackedVehicle
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningTrackedVehicle? CreateDrawningEntityFighter(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityTrackedVehicle? fighter = EntityFighter.CreateEntityFighter(strs);
if (fighter != null)
{
return new DrawingEntityFighter((EntityFighter)fighter);
}
fighter = EntityTrackedVehicle.CreateEntityTrackedVehicle(strs);
if (fighter != null)
{
return new DrawningTrackedVehicle(fighter);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningStormtrooper">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningTrackedVehicle drawningBaseStormtrooper)
{
string[]? array = drawningBaseStormtrooper?.EntityTrackedVehicle?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}
internal class DrawingEntityFighter : DrawningTrackedVehicle
{
public DrawingEntityFighter(EntityTrackedVehicle fighter) : base(fighter)
{
}
}

View File

@ -1,4 +1,7 @@

using static System.Reflection.Metadata.BlobBuilder;
using System.Net.Sockets;
namespace lab1.Entities;
/// <summary>
/// Класс-сущность "Истребитель"
@ -15,6 +18,10 @@ public class EntityFighter : EntityTrackedVehicle
/// Признак (опция) наличия ковша
/// </summary>
public bool Kovsh { get; private set; }
public void setBodyTankColor(Color color)
{
AdditionalColor = color;
}
/// <summary>
/// Признак (опция) наличия опор для фиксации
/// </summary>
@ -39,6 +46,36 @@ public class EntityFighter : EntityTrackedVehicle
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityFighter), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, Kovsh.ToString(), Otval.ToString() };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityFighter? CreateEntityStormtrooper(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntityFighter))
{
return null;
}
return new EntityFighter(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]));
}
internal static EntityTrackedVehicle? CreateEntityFighter(string[] strs)
{
throw new NotImplementedException();
}
}

View File

@ -27,6 +27,10 @@ public class EntityTrackedVehicle
/// Шаг перемещения истребителя
/// </summary>
public double Step => Speed * 100 / Weight;
public void setBodyColor(Color color)
{
BodyColor = color;
}
/// <summary>
/// Конструктор сущности
@ -42,4 +46,32 @@ public class EntityTrackedVehicle
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityTrackedVehicle), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityTrackedVehicle? CreateEntityBaseStormtrooper(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(EntityTrackedVehicle))
{
return null;
}
return new EntityTrackedVehicle(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
internal static EntityTrackedVehicle? CreateEntityTrackedVehicle(string[] strs)
{
throw new NotImplementedException();
}
}

View File

@ -30,7 +30,6 @@
{
groupBoxTools = new GroupBox();
panelCompanyTools = new Panel();
buttonAddFighter = new Button();
buttonAddTrackedVehicle = new Button();
buttonRefresh = new Button();
maskedTextBox = new MaskedTextBox();
@ -47,10 +46,17 @@
labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
SaveToolStripMenuItem = new ToolStripMenuItem();
LoadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// groupBoxTools
@ -60,16 +66,15 @@
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(635, 0);
groupBoxTools.Location = new Point(635, 33);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(297, 615);
groupBoxTools.Size = new Size(297, 582);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonAddFighter);
panelCompanyTools.Controls.Add(buttonAddTrackedVehicle);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(maskedTextBox);
@ -81,17 +86,6 @@
panelCompanyTools.Size = new Size(282, 273);
panelCompanyTools.TabIndex = 10;
//
// buttonAddFighter
//
buttonAddFighter.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddFighter.Location = new Point(6, 59);
buttonAddFighter.Name = "buttonAddFighter";
buttonAddFighter.Size = new Size(273, 59);
buttonAddFighter.TabIndex = 2;
buttonAddFighter.Text = "Добавление гусеничной машины с оборудованием";
buttonAddFighter.UseVisualStyleBackColor = true;
buttonAddFighter.Click += ButtonAddFighter_Click;
//
// buttonAddTrackedVehicle
//
buttonAddTrackedVehicle.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
@ -254,13 +248,55 @@
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0);
pictureBox.Location = new Point(0, 33);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(635, 615);
pictureBox.Size = new Size(635, 582);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
pictureBox.Click += pictureBox1_Click;
//
// menuStrip
//
menuStrip.ImageScalingSize = new Size(24, 24);
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(932, 33);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { SaveToolStripMenuItem, LoadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(69, 29);
файлToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
SaveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
SaveToolStripMenuItem.Size = new Size(273, 34);
SaveToolStripMenuItem.Text = "Сохранение";
SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// LoadToolStripMenuItem
//
LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
LoadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
LoadToolStripMenuItem.Size = new Size(273, 34);
LoadToolStripMenuItem.Text = "Загрузка";
LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog1";
openFileDialog.Filter = "txt file | *txt";
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *txt";
//
// FormTrackedVehicleCollection
//
AutoScaleDimensions = new SizeF(10F, 25F);
@ -268,6 +304,8 @@
ClientSize = new Size(932, 615);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormTrackedVehicleCollection";
Text = "Коллекция гусеничных машин";
Load += FormTrackedVehicleCollection_Load;
@ -277,7 +315,10 @@
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
@ -285,7 +326,6 @@
private GroupBox groupBoxTools;
private ComboBox comboBoxSelectorCompany;
private Button buttonAddTrackedVehicle;
private Button buttonAddFighter;
private PictureBox pictureBox;
private Button buttonRemoveTrackedVehicle;
private MaskedTextBox maskedTextBox;
@ -301,5 +341,11 @@
private Button button1CreateCompany;
private Button buttonCollectionDel;
private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
}
}

View File

@ -41,43 +41,28 @@ public partial class FormTrackedVehicleCollection : Form
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddTrackedVehicle_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningTrackedVehicle));
/// <summary>
/// Добавление истребителя
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddFighter_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningEntityFighter));
private void ButtonAddTrackedVehicle_Click(object sender, EventArgs e)
{
{
FormTrackedVehicleConfig form = new();
form.Show();
// передать метод ✔
form.AddEvent(SetTrackedVehicle);
}
}
/// <summary>
/// Создание объекта класса-перемещения
/// Добавление лодки в коллекцию
/// </summary>
/// <param name="type"></param>
private void CreateObject(string type)
/// <param name="boat"></param>
private void SetTrackedVehicle(DrawningTrackedVehicle trackedVehicle)
{
if (_company == null)
if (_company == null || trackedVehicle == null)
{
return;
}
Random random = new();
DrawningTrackedVehicle drawningTrackedVehicle;
switch (type)
{
case nameof(DrawningTrackedVehicle):
drawningTrackedVehicle = new DrawningTrackedVehicle(random.Next(100, 300), random.Next(1000, 3000), GetColor(random));
break;
case nameof(DrawningEntityFighter):
//TODO Выбор цветов
drawningTrackedVehicle = new DrawningEntityFighter(random.Next(100, 300), random.Next(1000, 3000),
GetColor(random),
GetColor(random),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
break;
default:
return;
}
if (_company + drawningTrackedVehicle != -1)
if (_company + trackedVehicle >= 0)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
@ -86,24 +71,6 @@ public partial class FormTrackedVehicleCollection : Form
{
MessageBox.Show("Не удалось добавить объект");
}
}
/// <summary>
/// Получение цвета
/// </summary>
/// <param name="random">Генератор случайных чисел</param>
/// <returns></returns>
private static Color GetColor(Random random)
{
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;
}
return color;
}
/// <summary>
@ -243,18 +210,16 @@ public partial class FormTrackedVehicleCollection : Form
// нужно убедиться, что есть выбранная коллекция
// спросить у пользователя через MessageBox, что он подтверждает, что хочет удалить запись
// удалить и обновить ListBox
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
if (_storageCollection.Keys.Contains(listBoxCollection.SelectedItem.ToString() ?? string.Empty))
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString() ?? string.Empty);
RerfreshListBoxItems();
}
/// <summary>
/// Обновление списка в listBoxCollection
/// </summary>
@ -298,5 +263,49 @@ public partial class FormTrackedVehicleCollection : Form
RerfreshListBoxItems();
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
// TODO продумать логику
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
{
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems();
}
else
{
MessageBox.Show("Загрузка не удалась", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.SaveData(saveFileDialog.FileName))
{
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>165, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>349, 20</value>
</metadata>
</root>

View File

@ -74,7 +74,7 @@
groupBoxConfig.Dock = DockStyle.Left;
groupBoxConfig.Location = new Point(0, 0);
groupBoxConfig.Name = "groupBoxConfig";
groupBoxConfig.Size = new Size(634, 212);
groupBoxConfig.Size = new Size(634, 420);
groupBoxConfig.TabIndex = 0;
groupBoxConfig.TabStop = false;
groupBoxConfig.Text = "Параметры";
@ -102,6 +102,7 @@
panelPurple.Name = "panelPurple";
panelPurple.Size = new Size(34, 37);
panelPurple.TabIndex = 5;
panelPurple.MouseDown += Panel_MouseDown;
//
// panelBlack
//
@ -110,6 +111,7 @@
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(34, 37);
panelBlack.TabIndex = 4;
panelBlack.MouseDown += Panel_MouseDown;
//
// panelGray
//
@ -118,6 +120,7 @@
panelGray.Name = "panelGray";
panelGray.Size = new Size(34, 37);
panelGray.TabIndex = 3;
panelGray.MouseDown += Panel_MouseDown;
//
// panelWhite
//
@ -126,6 +129,7 @@
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(34, 37);
panelWhite.TabIndex = 2;
panelWhite.MouseDown += Panel_MouseDown;
//
// panelYellow
//
@ -134,6 +138,7 @@
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(34, 37);
panelYellow.TabIndex = 1;
panelYellow.MouseDown += Panel_MouseDown;
//
// panelBlue
//
@ -150,6 +155,7 @@
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(34, 37);
panelGreen.TabIndex = 1;
panelGreen.MouseDown += Panel_MouseDown;
//
// panelRed
//
@ -158,6 +164,7 @@
panelRed.Name = "panelRed";
panelRed.Size = new Size(34, 37);
panelRed.TabIndex = 0;
panelRed.MouseDown += Panel_MouseDown;
//
// checkBoxOtval
//
@ -243,22 +250,23 @@
//
pictureBoxObject.Location = new Point(659, 75);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(185, 78);
pictureBoxObject.Size = new Size(290, 227);
pictureBoxObject.TabIndex = 1;
pictureBoxObject.TabStop = false;
//
// buttonAdd
//
buttonAdd.Location = new Point(640, 172);
buttonAdd.Location = new Point(640, 341);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(106, 34);
buttonAdd.TabIndex = 2;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += buttonAdd_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(752, 172);
buttonCancel.Location = new Point(752, 341);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(103, 34);
buttonCancel.TabIndex = 3;
@ -272,13 +280,14 @@
panelObject1.Controls.Add(labelBodyColor);
panelObject1.Location = new Point(644, 12);
panelObject1.Name = "panelObject1";
panelObject1.Size = new Size(211, 154);
panelObject1.Size = new Size(512, 323);
panelObject1.TabIndex = 4;
panelObject1.DragDrop += panelObject1_DragDrop;
panelObject1.DragDrop += PanelObject1_DragDrop;
panelObject1.DragEnter += PanelObject1_DragEnter;
//
// labelAdditionalColor
//
labelAdditionalColor.AllowDrop = true;
labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
labelAdditionalColor.Location = new Point(102, 9);
labelAdditionalColor.Name = "labelAdditionalColor";
@ -286,9 +295,13 @@
labelAdditionalColor.TabIndex = 2;
labelAdditionalColor.Text = "Доп. Цвет";
labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter;
labelAdditionalColor.Click += labelAdditionalColor_Click;
labelAdditionalColor.DragDrop += labelAdditionalColor_DragDrop;
labelAdditionalColor.DragEnter += labelAdditionalColor_DragEnter;
//
// labelBodyColor
//
labelBodyColor.AllowDrop = true;
labelBodyColor.BorderStyle = BorderStyle.FixedSingle;
labelBodyColor.Location = new Point(3, 9);
labelBodyColor.Name = "labelBodyColor";
@ -296,17 +309,19 @@
labelBodyColor.TabIndex = 1;
labelBodyColor.Text = "Цвет";
labelBodyColor.TextAlign = ContentAlignment.MiddleCenter;
labelBodyColor.DragDrop += labelBodyColor_DragDrop;
labelBodyColor.DragEnter += LabelBodyColor_DragEnter;
//
// FormTrackedVehicleConfig
//
AutoScaleDimensions = new SizeF(10F, 25F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(867, 212);
Controls.Add(panelObject1);
ClientSize = new Size(1168, 420);
Controls.Add(pictureBoxObject);
Controls.Add(buttonCancel);
Controls.Add(buttonAdd);
Controls.Add(pictureBoxObject);
Controls.Add(groupBoxConfig);
Controls.Add(panelObject1);
Name = "FormTrackedVehicleConfig";
Text = "Создание объекта";
Load += FormTrackedVehicleConfig_Load;

View File

@ -1,4 +1,5 @@
using lab1.Drawnings;
using lab1.Entities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@ -19,14 +20,18 @@ public partial class FormTrackedVehicleConfig : Form
/// <summary>
/// Объект - прорисовка гусеничной машины
/// </summary>
private DrawningTrackedVehicle _trackedVehicle = null;
private DrawningTrackedVehicle? _trackedVehicle;
/// <summary>
/// Событие для предачи объекта
/// </summary>
private event TrackedVehicleDelegate? TrackedVehicleDelegate;
/// <summary>
/// Конструктор
/// </summary>
public FormTrackedVehicleConfig()
{
InitializeComponent();
panelRed.MouseDown += Panel_MouseDown;
panelGreen.MouseDown += Panel_MouseDown;
panelBlue.MouseDown += Panel_MouseDown;
@ -35,11 +40,15 @@ public partial class FormTrackedVehicleConfig : Form
panelGray.MouseDown += Panel_MouseDown;
panelBlack.MouseDown += Panel_MouseDown;
panelPurple.MouseDown += Panel_MouseDown;
//TODO buttonCancel.Click with lambda с закрытием формы
buttonCancel.Click += (object sender, EventArgs e) => Close();
InitializeComponent();
buttonCancel.Click += (sender, e) => Close();
}
/// <summary>
/// Привязка внешнего метода к событию
/// </summary>
/// <param name="trackedVehicleDelegate"></param>
///
/// <summary>
/// Прорисовка объекта
@ -78,12 +87,12 @@ public partial class FormTrackedVehicleConfig : Form
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void panelObject1_DragDrop(object sender, DragEventArgs e)
private void PanelObject1_DragDrop(object sender, DragEventArgs e)
{
switch (e.Data?.GetData(DataFormats.Text)?.ToString())
{
case "labelSimpleObject":
case "LabelSimpleObject":
_trackedVehicle = new DrawningTrackedVehicle((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White);
break;
case "LabelModifiedObject":
@ -106,7 +115,7 @@ public partial class FormTrackedVehicleConfig : Form
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Panel_MouseDown(object sender, MouseEventArgs e)
private void Panel_MouseDown(object? sender, MouseEventArgs e)
{
//TODO отправка цвета в Drag&Drop
(sender as Control)?.DoDragDrop((sender as Control).BackColor, DragDropEffects.Move | DragDropEffects.Copy);
@ -123,4 +132,58 @@ public partial class FormTrackedVehicleConfig : Form
e.Effect = DragDropEffects.None;
}
}
public void AddEvent(TrackedVehicleDelegate trainDelegate)
{
TrackedVehicleDelegate += trainDelegate;
}
private void labelAdditionalColor_DragDrop(object sender, DragEventArgs e)
{
if (_trackedVehicle.EntityTrackedVehicle is EntityFighter _rockets)
{
_rockets.setBodyTankColor((Color)e.Data.GetData(typeof(Color)));
}
DrawObject();
}
private void labelBodyColor_DragDrop(object sender, DragEventArgs e)
{
if (_trackedVehicle != null)
{
_trackedVehicle.EntityTrackedVehicle.setBodyColor((Color)e.Data.GetData(typeof(Color)));
DrawObject();
}
}
private void labelAdditionalColor_DragEnter(object sender, DragEventArgs e)
{
if (_trackedVehicle is DrawningEntityFighter)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
}
/// <summary>
/// Передача объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAdd_Click(object sender, EventArgs e)
{
if (_trackedVehicle != null)
{
TrackedVehicleDelegate?.Invoke(_trackedVehicle);
Close();
}
}
private void labelAdditionalColor_Click(object sender, EventArgs e)
{
}
}

View File

@ -0,0 +1,15 @@
using lab1.Drawnings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace lab1;
/// <summary>
/// Делегат передачи объекта класса-прорисовки
/// </summary>
/// <param name="trackedVehicle"></param>
public delegate void TrackedVehicleDelegate(DrawningTrackedVehicle trackedVehicle);