This commit is contained in:
dyakonovr 2023-11-18 17:07:10 +04:00
parent b2e5c3e9b5
commit e6406130fd
8 changed files with 328 additions and 44 deletions

View File

@ -17,6 +17,7 @@ namespace ProjectTank.DrawningObjects
EntityTankBase = new EntityTank(speed, weight, bodyColor, additionalColor, isTankTower, isAntiAirforceGun);
}
public override void DrawTransport(Graphics g)
{
if (EntityTankBase is not EntityTank tank) return;

View File

@ -0,0 +1,58 @@
using ProjectTank.DrawningObjects;
using ProjectTank.Entities;
namespace ProjectTank.Drawnings
{
public static class ExtentionDrawningTankBase
{
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
/// <returns>Объект</returns>
public static DrawningTankBase? CreateDrawningTankBase(this string info, char
separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawningTankBase(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="drawningCar">Сохраняемый объект</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningTankBase drawningTankBase, char separatorForObject)
{
var tankBase = drawningTankBase.EntityTankBase;
if (tankBase == null)
{
return string.Empty;
}
var str = $"{tankBase.Speed}{separatorForObject}{tankBase.Weight}{separatorForObject}{tankBase.BodyColor.Name}";
if (tankBase is not EntityTank tank)
{
return str;
}
return $"{str}{separatorForObject}{tank.AdditionalColor.Name}{separatorForObject}{tank.AntiAirforceGun}{separatorForObject}{tank.TankTower}";
}
}
}

View File

@ -29,39 +29,38 @@
private void InitializeComponent()
{
pictureBoxCollection = new PictureBox();
label1 = new Label();
refreshObjectsButton = new Button();
deleteTankButton = new Button();
addTankButton = new Button();
maskedTextBoxNumber = new TextBox();
label2 = new Label();
objectsLabel = new Label();
textBoxStorageName = new TextBox();
addObjectButton = new Button();
listBoxStorages = new ListBox();
deleteObjectButton = new Button();
toolsGroupBox = new GroupBox();
menuStrip = new MenuStrip();
fileToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
toolsGroupBox.SuspendLayout();
menuStrip.SuspendLayout();
SuspendLayout();
//
// pictureBoxCollection
//
pictureBoxCollection.Location = new Point(6, 4);
pictureBoxCollection.Location = new Point(6, 32);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(760, 475);
pictureBoxCollection.TabIndex = 0;
pictureBoxCollection.TabStop = false;
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(775, 9);
label1.Name = "label1";
label1.Size = new Size(103, 20);
label1.TabIndex = 1;
label1.Text = "Инструменты";
//
// refreshObjectsButton
//
refreshObjectsButton.Location = new Point(775, 448);
refreshObjectsButton.Location = new Point(6, 410);
refreshObjectsButton.Name = "refreshObjectsButton";
refreshObjectsButton.Size = new Size(139, 29);
refreshObjectsButton.TabIndex = 4;
@ -71,7 +70,7 @@
//
// deleteTankButton
//
deleteTankButton.Location = new Point(775, 393);
deleteTankButton.Location = new Point(6, 377);
deleteTankButton.Name = "deleteTankButton";
deleteTankButton.Size = new Size(139, 29);
deleteTankButton.TabIndex = 5;
@ -81,7 +80,7 @@
//
// addTankButton
//
addTankButton.Location = new Point(775, 306);
addTankButton.Location = new Point(6, 307);
addTankButton.Name = "addTankButton";
addTankButton.Size = new Size(139, 29);
addTankButton.TabIndex = 6;
@ -91,30 +90,30 @@
//
// maskedTextBoxNumber
//
maskedTextBoxNumber.Location = new Point(775, 360);
maskedTextBoxNumber.Location = new Point(6, 344);
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(139, 27);
maskedTextBoxNumber.TabIndex = 7;
//
// label2
// objectsLabel
//
label2.AutoSize = true;
label2.Location = new Point(775, 51);
label2.Name = "label2";
label2.Size = new Size(66, 20);
label2.TabIndex = 8;
label2.Text = "Наборы";
objectsLabel.AutoSize = true;
objectsLabel.Location = new Point(6, 30);
objectsLabel.Name = "objectsLabel";
objectsLabel.Size = new Size(66, 20);
objectsLabel.TabIndex = 8;
objectsLabel.Text = "Наборы";
//
// textBoxStorageName
//
textBoxStorageName.Location = new Point(775, 74);
textBoxStorageName.Location = new Point(6, 67);
textBoxStorageName.Name = "textBoxStorageName";
textBoxStorageName.Size = new Size(139, 27);
textBoxStorageName.TabIndex = 9;
//
// addObjectButton
//
addObjectButton.Location = new Point(775, 107);
addObjectButton.Location = new Point(6, 100);
addObjectButton.Name = "addObjectButton";
addObjectButton.Size = new Size(139, 29);
addObjectButton.TabIndex = 10;
@ -126,7 +125,7 @@
//
listBoxStorages.FormattingEnabled = true;
listBoxStorages.ItemHeight = 20;
listBoxStorages.Location = new Point(775, 142);
listBoxStorages.Location = new Point(6, 135);
listBoxStorages.Name = "listBoxStorages";
listBoxStorages.Size = new Size(139, 84);
listBoxStorages.TabIndex = 11;
@ -134,7 +133,7 @@
//
// deleteObjectButton
//
deleteObjectButton.Location = new Point(775, 232);
deleteObjectButton.Location = new Point(6, 234);
deleteObjectButton.Name = "deleteObjectButton";
deleteObjectButton.Size = new Size(139, 29);
deleteObjectButton.TabIndex = 12;
@ -142,25 +141,80 @@
deleteObjectButton.UseVisualStyleBackColor = true;
deleteObjectButton.Click += ButtonDelObject_Click;
//
// toolsGroupBox
//
toolsGroupBox.Controls.Add(objectsLabel);
toolsGroupBox.Controls.Add(refreshObjectsButton);
toolsGroupBox.Controls.Add(deleteTankButton);
toolsGroupBox.Controls.Add(maskedTextBoxNumber);
toolsGroupBox.Controls.Add(deleteObjectButton);
toolsGroupBox.Controls.Add(addTankButton);
toolsGroupBox.Controls.Add(textBoxStorageName);
toolsGroupBox.Controls.Add(listBoxStorages);
toolsGroupBox.Controls.Add(addObjectButton);
toolsGroupBox.Location = new Point(775, 32);
toolsGroupBox.Name = "toolsGroupBox";
toolsGroupBox.Size = new Size(154, 472);
toolsGroupBox.TabIndex = 13;
toolsGroupBox.TabStop = false;
toolsGroupBox.Text = "Инструменты";
//
// menuStrip
//
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(935, 28);
menuStrip.TabIndex = 14;
menuStrip.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
fileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { loadToolStripMenuItem, saveToolStripMenuItem });
fileToolStripMenuItem.Name = "fileToolStripMenuItem";
fileToolStripMenuItem.Size = new Size(59, 24);
fileToolStripMenuItem.Text = "Файл";
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.Size = new Size(166, 26);
loadToolStripMenuItem.Text = "Загрузить";
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.Size = new Size(166, 26);
saveToolStripMenuItem.Text = "Сохранить";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog";
openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// FormTankCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(926, 486);
Controls.Add(deleteObjectButton);
Controls.Add(listBoxStorages);
Controls.Add(addObjectButton);
Controls.Add(textBoxStorageName);
Controls.Add(label2);
Controls.Add(maskedTextBoxNumber);
Controls.Add(addTankButton);
Controls.Add(deleteTankButton);
Controls.Add(refreshObjectsButton);
Controls.Add(label1);
ClientSize = new Size(935, 516);
Controls.Add(toolsGroupBox);
Controls.Add(pictureBoxCollection);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormTankCollection";
Text = "Набор танков";
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
toolsGroupBox.ResumeLayout(false);
toolsGroupBox.PerformLayout();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
@ -168,15 +222,21 @@
#endregion
private PictureBox pictureBoxCollection;
private Label label1;
private Button refreshObjectsButton;
private Button deleteTankButton;
private Button addTankButton;
private TextBox maskedTextBoxNumber;
private Label label2;
private Label objectsLabel;
private TextBox textBoxStorageName;
private Button addObjectButton;
private ListBox listBoxStorages;
private Button deleteObjectButton;
private GroupBox toolsGroupBox;
private MenuStrip menuStrip;
private ToolStripMenuItem fileToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
}
}

View File

@ -1,6 +1,7 @@
using ProjectTank.DrawningObjects;
using ProjectTank.Generics;
using ProjectTank.MovementStrategy;
using System.Windows.Forms;
namespace ProjectTank
{
@ -143,7 +144,46 @@ namespace ProjectTank
pictureBoxCollection.Image = obj.ShowTanks();
}
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

@ -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>144, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>303, 17</value>
</metadata>
</root>

View File

@ -1,5 +1,4 @@
using ProjectTank.DrawningObjects;
using System.Windows.Forms;
namespace ProjectTank
{
@ -16,6 +15,7 @@ namespace ProjectTank
/// Событие
/// </summary>
private event Action<DrawningTankBase>? EventAddTank;
/// <summary>
/// Конструктор
/// </summary>
@ -57,6 +57,7 @@ namespace ProjectTank
private void PanelColor_MouseDown(object sender, MouseEventArgs e)
{
(sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Передаем информацию при нажатии на Label
@ -65,7 +66,8 @@ namespace ProjectTank
/// <param name="e"></param>
private void LabelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label)?.DoDragDrop((sender as Label)?.Name, DragDropEffects.Move | DragDropEffects.Copy);
(sender as Label)?.DoDragDrop((sender as Label)?.Name,
DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому)

View File

@ -31,6 +31,10 @@ namespace ProjectTank.Generics
/// </summary>
private readonly SetGeneric<T> _collection;
/// <summary>
/// Получение объектов коллекции
/// </summary>
public IEnumerable<T?> GetTanks => _collection.GetTanks();
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>

View File

@ -1,5 +1,7 @@
using ProjectTank.DrawningObjects;
using ProjectTank.Drawnings;
using ProjectTank.MovementStrategy;
using System.Text;
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>
@ -71,5 +85,101 @@ 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, TanksGenericCollection<DrawningTankBase, DrawningObjectTank>> record in _tankStorages)
{
StringBuilder records = new();
foreach (DrawningTankBase? elem in record.Value.GetTanks)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
return false;
}
string toWrite = $"TanksStorage{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;
}
/// <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(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("TanksStorage"))
{
return false;
}
_tankStorages.Clear();
do
{
string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
str = sr.ReadLine();
continue;
}
TanksGenericCollection<DrawningTankBase, DrawningObjectTank> collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawningTankBase? tank =
elem?.CreateDrawningTankBase(_separatorForObject, _pictureWidth, _pictureHeight);
if (tank != null)
{
if (!(collection + tank))
{
return false;
}
}
}
_tankStorages.Add(record[0], collection);
str = sr.ReadLine();
} while (str != null);
}
return true;
}
}
}