lab 6 is done

This commit is contained in:
vladimir_zinovev 2023-12-14 21:53:21 +04:00
parent ef62f8b016
commit 748e7b509f
7 changed files with 295 additions and 31 deletions

View File

@ -39,11 +39,18 @@
this.ButtonRemoveArmoredTransport = new System.Windows.Forms.Button();
this.maskedTextBoxNumber = new System.Windows.Forms.TextBox();
this.ButtonAddArmoredTransport = new System.Windows.Forms.Button();
this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
this.contextMenuStrip = new System.Windows.Forms.ContextMenuStrip(this.components);
this.pictureBoxCollection = new System.Windows.Forms.PictureBox();
this.menuStrip = new System.Windows.Forms.MenuStrip();
this.ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.SaveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.LoadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.ArmoredTransportCollectionFormToolsGroup.SuspendLayout();
this.groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).BeginInit();
this.menuStrip.SuspendLayout();
this.SuspendLayout();
//
// ArmoredTransportCollectionFormToolsGroup
@ -160,11 +167,11 @@
this.ButtonAddArmoredTransport.UseVisualStyleBackColor = true;
this.ButtonAddArmoredTransport.Click += new System.EventHandler(this.ButtonAddArmoredTransport_Click);
//
// contextMenuStrip1
// contextMenuStrip
//
this.contextMenuStrip1.ImageScalingSize = new System.Drawing.Size(32, 32);
this.contextMenuStrip1.Name = "contextMenuStrip1";
this.contextMenuStrip1.Size = new System.Drawing.Size(61, 4);
this.contextMenuStrip.ImageScalingSize = new System.Drawing.Size(32, 32);
this.contextMenuStrip.Name = "contextMenuStrip1";
this.contextMenuStrip.Size = new System.Drawing.Size(61, 4);
//
// pictureBoxCollection
//
@ -176,20 +183,67 @@
this.pictureBoxCollection.TabIndex = 2;
this.pictureBoxCollection.TabStop = false;
//
// menuStrip
//
this.menuStrip.ImageScalingSize = new System.Drawing.Size(32, 32);
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.ToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(1492, 40);
this.menuStrip.TabIndex = 3;
this.menuStrip.Text = "menuStrip1";
//
// ToolStripMenuItem
//
this.ToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.SaveToolStripMenuItem,
this.LoadToolStripMenuItem});
this.ToolStripMenuItem.Name = "ToolStripMenuItem";
this.ToolStripMenuItem.Size = new System.Drawing.Size(90, 36);
this.ToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(359, 44);
this.SaveToolStripMenuItem.Text = "Сохранить";
this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// LoadToolStripMenuItem
//
this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(359, 44);
this.LoadToolStripMenuItem.Text = "Загрузить";
this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
// openFileDialog
//
this.openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
this.saveFileDialog.FileName = "Storage";
this.saveFileDialog.Filter = "txt file | *.txt";
//
// ArmoredTransportCollectionForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(13F, 32F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1492, 873);
this.Controls.Add(this.menuStrip);
this.Controls.Add(this.ArmoredTransportCollectionFormToolsGroup);
this.Controls.Add(this.pictureBoxCollection);
this.MainMenuStrip = this.menuStrip;
this.Name = "ArmoredTransportCollectionForm";
this.Text = "Коллекция бронированного транспорта";
this.Text = "ArmoredTransportCollectionForm";
this.ArmoredTransportCollectionFormToolsGroup.ResumeLayout(false);
this.ArmoredTransportCollectionFormToolsGroup.PerformLayout();
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).EndInit();
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
@ -202,12 +256,18 @@
private Button ButtonRemoveArmoredTransport;
private TextBox maskedTextBoxNumber;
private Button ButtonAddArmoredTransport;
private ContextMenuStrip contextMenuStrip1;
private ContextMenuStrip contextMenuStrip;
private PictureBox pictureBoxCollection;
private GroupBox groupBox1;
private TextBox textBoxStorageName;
private ListBox listBoxStorages;
private Button buttonDelObject;
private Button buttonAddObject;
private MenuStrip menuStrip;
private ToolStripMenuItem ToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
}
}

View File

@ -33,13 +33,11 @@ namespace ProjectTank
{
listBoxStorages.Items.Add(_storage.Keys[i]);
}
if (listBoxStorages.Items.Count > 0 && (index == -1 || index
>= listBoxStorages.Items.Count))
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)
else if (listBoxStorages.Items.Count > 0 && index > -1 && index < listBoxStorages.Items.Count)
{
listBoxStorages.SelectedIndex = index;
}
@ -80,14 +78,10 @@ namespace ProjectTank
{
return;
}
if (MessageBox.Show($"Удалить объект: {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(listBoxStorages.SelectedItem.ToString()??string.Empty);
_storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty);
ReloadObjects();
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
@ -179,5 +173,52 @@ namespace ProjectTank
}
pictureBoxCollection.Image = obj.ShowArmoredTransports();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_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);
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.LoadData(openFileDialog.FileName))
{
MessageBox.Show("Загрузка прошла успешно", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Information);
foreach (var collection in _storage.Keys)
{
listBoxStorages.Items.Add(collection);
}
}
else
{
MessageBox.Show("Ошибка при загрузке", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}

View File

@ -57,7 +57,16 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="contextMenuStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<metadata name="contextMenuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>296, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>494, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>743, 17</value>
</metadata>
</root>

View File

@ -81,7 +81,7 @@ namespace ProjectTank
private void LabelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label)?.DoDragDrop((sender as Label)?.Name,
DragDropEffects.Move | DragDropEffects.Copy);
DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому)
@ -121,18 +121,6 @@ namespace ProjectTank
{
(sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor, DragDropEffects.Move | DragDropEffects.Copy);
}
private void allowPanel_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(DataFormats.Text) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
/// <summary>
/// Добавление машины
/// </summary>

View File

@ -51,6 +51,10 @@ namespace ProjectTank.Generics
_collection = new SetGeneric<T>(width * height);
}
/// <summary>
/// Получение объектов коллекции
/// </summary>
public IEnumerable<T?> GetArmoredTransports => _collection.GetArmoredTransports();
/// <summary>
/// Перегрузка оператора сложения
/// </summary>
/// <param name="collect"></param>

View File

@ -1,5 +1,7 @@
using System;
using System.Text;
using ProjectTank.DrawningObjects;
using ProjectTank.Drawnings;
using ProjectTank.MovementStrategy;
namespace ProjectTank.Generics
@ -26,6 +28,18 @@ namespace ProjectTank.Generics
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private static readonly char _separatorForKeyValue = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char _separatorRecords = ';';
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Конструктор
/// </summary>
/// <param name="pictureWidth"></param>
@ -72,5 +86,89 @@ namespace ProjectTank.Generics
return null;
}
}
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
{
if (File.Exists(filename)) //проверка на существование файла
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string,ArmoredTransportsGenericCollection<DrawningArmoredTransport, DrawningObjectArmoredTransport>> record in _armoredTransportStorages)
{ //создается тип пара ключ значение, который представляет строку и на каждой итерации берется элемент record коллекции _armoredTransportStorages
StringBuilder records = new();
foreach (DrawningArmoredTransport? elem in record.Value.GetArmoredTransports) // проход по списку коллекции с получением значения объекта
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}"); //добавление в стрингбилдер свойств объекта с разделителем : и в конце ;
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}"); // добавление значения словаря ключа в начало и разделение разделитем
}
if (data.Length == 0)
{
return false;
}
string toWrite = $"ArmoredTransportsStorage{Environment.NewLine}{data}";
var strs = toWrite.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); // разделение по символам новой строки
using (StreamWriter sw = new(filename))
{
foreach (var str in strs)
{
sw.WriteLine(str);
}
}
return true;
}
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
}
using (StreamReader sr = new(filename))
{
string str = sr.ReadLine();
var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
return false;
}
if (!strs[0].StartsWith("ArmoredTransportsStorage"))
{
//если нет такой записи, то это не те данные
return false;
}
_armoredTransportStorages.Clear();
do
{
string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
str = sr.ReadLine();
continue;
}
ArmoredTransportsGenericCollection<DrawningArmoredTransport, DrawningObjectArmoredTransport>
collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawningArmoredTransport? armoredTransport = elem?.CreateDrawningArmoredTransport(_separatorForObject, _pictureWidth, _pictureHeight);
if (armoredTransport != null)
{
if (!(collection + armoredTransport))
{
return false;
}
}
}
_armoredTransportStorages.Add(record[0], collection);
str = sr.ReadLine();
} while (str != null);
}
return true;
}
}
}

View File

@ -0,0 +1,64 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectTank.Entities;
using ProjectTank.DrawningObjects;
namespace ProjectTank.Drawnings
{
public static class ExtentionDrawningArmoredTransport
{
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
/// <returns>Объект</returns>
public static DrawningArmoredTransport? CreateDrawningArmoredTransport(this string info, char separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawningArmoredTransport(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
}
if (strs.Length == 6)
{
return new DrawningTank(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>
/// <param name="drawningArmoredTransport">Сохраняемый объект</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningArmoredTransport drawningArmoredTransport, char separatorForObject)
{
var armoredTransport = drawningArmoredTransport.EntityArmoredTransport;
if (armoredTransport == null)
{
return string.Empty;
}
var str =
$"{armoredTransport.Speed}{separatorForObject}{armoredTransport.Weight}{separatorForObject}{armoredTransport.BodyColor.Name}";
if (armoredTransport is not EntityTank tank)
{
return str;
}
return
$"{str}{separatorForObject}{tank.AdditionalColor.Name}" +
$"{separatorForObject}{tank.Gun}" +
$"{separatorForObject}{tank.MachineGun}";
}
}
}