This commit is contained in:
marusya 2023-11-12 18:00:42 +04:00
parent 7725cf692a
commit 733f7f5a51
7 changed files with 293 additions and 10 deletions

View File

@ -95,7 +95,7 @@ namespace SelfPropelledArtilleryUnit.DrawningObjects
public void SetPosition(int x, int y) public void SetPosition(int x, int y)
{ {
// TODO: Изменение x, y, если при установке объект выходит за границы // TODO: Изменение x, y, если при установке объект выходит за границы
if (x < 0 || y < 0 || x + _ustaWidth > _pictureWidth || y + _ustaHeight > _pictureHeight) if (x < 0 || y < 0 )
{ {
x = 10; x = 10;
y = 10; y = 10;

View File

@ -0,0 +1,61 @@
using SelfPropelledArtilleryUnit.Entities;
namespace SelfPropelledArtilleryUnit.DrawningObjects
{
/// <summary>
/// Расширение для класса EntityUsta
/// </summary>
public static class ExtentionDrawningUsta
{
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
/// <returns>Объект</returns>
public static DrawningUsta? CreateDrawningUsta(this string info, char
separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawningUsta(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
}
else if (strs.Length == 6)
{
return new DrawningUstaBat(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="drawningUsta">Сохраняемый объект</param>
/// <param name="separatorForObject">Разделитель даннных</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningUsta drawningUsta,
char separatorForUsta)
{
var usta = drawningUsta.EntityUsta;
if (usta == null)
{
return string.Empty;
}
var str =
$"{usta.Speed}{separatorForUsta}{usta.Weight}{separatorForUsta}{usta.BodyColor.Name}";
if (usta is not EntityUstaBat sportUsta)
{
return str;
}
return $"{str}{separatorForUsta}{sportUsta.AdditionalColor.Name}{separatorForUsta}{sportUsta.BodyKit}{separatorForUsta}{sportUsta.Pushka}";
}
}
}

View File

@ -39,14 +39,21 @@
ButtonDelObject = new Button(); ButtonDelObject = new Button();
ButtonAddObject = new Button(); ButtonAddObject = new Button();
textBoxStorageName = new TextBox(); textBoxStorageName = new TextBox();
menuStrip = new MenuStrip();
fileToolStripMenuItem = new ToolStripMenuItem();
SaveToolStripMenuItem = new ToolStripMenuItem();
LoadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
groupBox1.SuspendLayout(); groupBox1.SuspendLayout();
groupBox2.SuspendLayout(); groupBox2.SuspendLayout();
menuStrip.SuspendLayout();
SuspendLayout(); SuspendLayout();
// //
// ButtonAddUsta // ButtonAddUsta
// //
ButtonAddUsta.Location = new Point(26, 314); ButtonAddUsta.Location = new Point(26, 366);
ButtonAddUsta.Name = "ButtonAddUsta"; ButtonAddUsta.Name = "ButtonAddUsta";
ButtonAddUsta.Size = new Size(166, 40); ButtonAddUsta.Size = new Size(166, 40);
ButtonAddUsta.TabIndex = 0; ButtonAddUsta.TabIndex = 0;
@ -56,7 +63,7 @@
// //
// ButtonRemoveUsta // ButtonRemoveUsta
// //
ButtonRemoveUsta.Location = new Point(26, 400); ButtonRemoveUsta.Location = new Point(26, 457);
ButtonRemoveUsta.Name = "ButtonRemoveUsta"; ButtonRemoveUsta.Name = "ButtonRemoveUsta";
ButtonRemoveUsta.Size = new Size(166, 39); ButtonRemoveUsta.Size = new Size(166, 39);
ButtonRemoveUsta.TabIndex = 1; ButtonRemoveUsta.TabIndex = 1;
@ -66,7 +73,7 @@
// //
// ButtonRefreshCollection // ButtonRefreshCollection
// //
ButtonRefreshCollection.Location = new Point(26, 478); ButtonRefreshCollection.Location = new Point(26, 502);
ButtonRefreshCollection.Name = "ButtonRefreshCollection"; ButtonRefreshCollection.Name = "ButtonRefreshCollection";
ButtonRefreshCollection.Size = new Size(166, 40); ButtonRefreshCollection.Size = new Size(166, 40);
ButtonRefreshCollection.TabIndex = 2; ButtonRefreshCollection.TabIndex = 2;
@ -86,7 +93,7 @@
// maskedTextBoxNumber // maskedTextBoxNumber
// //
maskedTextBoxNumber.Font = new Font("Showcard Gothic", 9F, FontStyle.Regular, GraphicsUnit.Point); maskedTextBoxNumber.Font = new Font("Showcard Gothic", 9F, FontStyle.Regular, GraphicsUnit.Point);
maskedTextBoxNumber.Location = new Point(56, 371); maskedTextBoxNumber.Location = new Point(58, 429);
maskedTextBoxNumber.Mask = "00"; maskedTextBoxNumber.Mask = "00";
maskedTextBoxNumber.Name = "maskedTextBoxNumber"; maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(100, 22); maskedTextBoxNumber.Size = new Size(100, 22);
@ -100,9 +107,10 @@
groupBox1.Controls.Add(ButtonRefreshCollection); groupBox1.Controls.Add(ButtonRefreshCollection);
groupBox1.Controls.Add(maskedTextBoxNumber); groupBox1.Controls.Add(maskedTextBoxNumber);
groupBox1.Controls.Add(ButtonRemoveUsta); groupBox1.Controls.Add(ButtonRemoveUsta);
groupBox1.Controls.Add(menuStrip);
groupBox1.Location = new Point(643, 12); groupBox1.Location = new Point(643, 12);
groupBox1.Name = "groupBox1"; groupBox1.Name = "groupBox1";
groupBox1.Size = new Size(209, 533); groupBox1.Size = new Size(209, 560);
groupBox1.TabIndex = 5; groupBox1.TabIndex = 5;
groupBox1.TabStop = false; groupBox1.TabStop = false;
groupBox1.Text = "Инструменты"; groupBox1.Text = "Инструменты";
@ -113,7 +121,7 @@
groupBox2.Controls.Add(ButtonDelObject); groupBox2.Controls.Add(ButtonDelObject);
groupBox2.Controls.Add(ButtonAddObject); groupBox2.Controls.Add(ButtonAddObject);
groupBox2.Controls.Add(textBoxStorageName); groupBox2.Controls.Add(textBoxStorageName);
groupBox2.Location = new Point(6, 22); groupBox2.Location = new Point(6, 64);
groupBox2.Name = "groupBox2"; groupBox2.Name = "groupBox2";
groupBox2.Size = new Size(197, 274); groupBox2.Size = new Size(197, 274);
groupBox2.TabIndex = 6; groupBox2.TabIndex = 6;
@ -157,6 +165,47 @@
textBoxStorageName.Size = new Size(158, 23); textBoxStorageName.Size = new Size(158, 23);
textBoxStorageName.TabIndex = 0; textBoxStorageName.TabIndex = 0;
// //
// menuStrip
//
menuStrip.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem });
menuStrip.Location = new Point(3, 19);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(203, 24);
menuStrip.TabIndex = 7;
menuStrip.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
fileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { SaveToolStripMenuItem, LoadToolStripMenuItem });
fileToolStripMenuItem.Name = "fileToolStripMenuItem";
fileToolStripMenuItem.Size = new Size(48, 20);
fileToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
SaveToolStripMenuItem.Size = new Size(180, 22);
SaveToolStripMenuItem.Text = "Сохранение";
SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// LoadToolStripMenuItem
//
LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
LoadToolStripMenuItem.Size = new Size(180, 22);
LoadToolStripMenuItem.Text = "Загрузка";
LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog1";
openFileDialog.Filter = "txt file | *.txt";
openFileDialog.Title = "Сохранить текстовый файл";
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
saveFileDialog.Title = "Выберите текстовый файл";
//
// FormSelfPropelledArtilleryUnitCollection // FormSelfPropelledArtilleryUnitCollection
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
@ -164,6 +213,7 @@
ClientSize = new Size(867, 584); ClientSize = new Size(867, 584);
Controls.Add(groupBox1); Controls.Add(groupBox1);
Controls.Add(pictureBoxCollection); Controls.Add(pictureBoxCollection);
MainMenuStrip = menuStrip;
Name = "FormSelfPropelledArtilleryUnitCollection"; Name = "FormSelfPropelledArtilleryUnitCollection";
Text = "Набор арт. установок"; Text = "Набор арт. установок";
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
@ -171,6 +221,8 @@
groupBox1.PerformLayout(); groupBox1.PerformLayout();
groupBox2.ResumeLayout(false); groupBox2.ResumeLayout(false);
groupBox2.PerformLayout(); groupBox2.PerformLayout();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false); ResumeLayout(false);
} }
@ -187,5 +239,11 @@
private ListBox listBoxStorage; private ListBox listBoxStorage;
private Button ButtonDelObject; private Button ButtonDelObject;
private Button ButtonAddObject; private Button ButtonAddObject;
private MenuStrip menuStrip;
private ToolStripMenuItem fileToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
} }
} }

View File

@ -131,7 +131,7 @@ namespace SelfPropelledArtilleryUnit
formSelfPropelledArtilleryUnitConfig.Show(); formSelfPropelledArtilleryUnitConfig.Show();
} }
/// <summary> /// <summary>
/// Удаление объекта из набора /// Удаление объекта из набора
/// </summary> /// </summary>
@ -185,6 +185,50 @@ namespace SelfPropelledArtilleryUnit
} }
pictureBoxCollection.Image = obj.ShowUsta(); pictureBoxCollection.Image = obj.ShowUsta();
} }
/// <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);
ReloadObjects();
}
else
{
MessageBox.Show("Ошибка при загрузке данных.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
} }
} }

View File

@ -117,4 +117,13 @@
<resheader name="writer"> <resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </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>126, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>259, 17</value>
</metadata>
</root> </root>

View File

@ -13,6 +13,11 @@ namespace SelfPropelledArtilleryUnit.Generics
where T : DrawningUsta where T : DrawningUsta
where U : IMoveableObject where U : IMoveableObject
{ {
/// <summary>
/// Получение объектов коллекции
/// </summary>
public IEnumerable<T?> GetUsta => _collection.GetUsta();
/// <summary> /// <summary>
/// Ширина окна прорисовки /// Ширина окна прорисовки
/// </summary> /// </summary>

View File

@ -1,8 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.IO;
using System.Text; using System.Text;
using System.Threading.Tasks;
using SelfPropelledArtilleryUnit.Drawnings; using SelfPropelledArtilleryUnit.Drawnings;
using SelfPropelledArtilleryUnit.MovementStrategy; using SelfPropelledArtilleryUnit.MovementStrategy;
@ -30,6 +29,18 @@ namespace SelfPropelledArtilleryUnit.Generics
/// </summary> /// </summary>
private readonly int _pictureHeight; private readonly int _pictureHeight;
/// <summary> /// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private static readonly char _separatorForKeyValue = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char _separatorRecords = ';';
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
/// <param name="pictureWidth"></param> /// <param name="pictureWidth"></param>
@ -84,6 +95,101 @@ namespace SelfPropelledArtilleryUnit.Generics
} }
} }
/// <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,
UstaGenericCollection<DrawningUsta, DrawningObjectUsta>> record in _ustaStorages)
{
StringBuilder records = new();
foreach (DrawningUsta? elem in record.Value.GetUsta)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
return false;
}
using FileStream fs = new(filename, FileMode.Create);
byte[] info = new
UTF8Encoding(true).GetBytes($"UstaStorage{Environment.NewLine}{data}");
fs.Write(info, 0, info.Length);
return true;
}
/// <summary>
/// Загрузка информации по установкам в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
}
string bufferTextFromFile = "";
using (FileStream fs = new(filename, FileMode.Open))
{
byte[] b = new byte[fs.Length];
UTF8Encoding temp = new(true);
while (fs.Read(b, 0, b.Length) > 0)
{
bufferTextFromFile += temp.GetString(b);
}
}
var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' },
StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
return false;
}
if (!strs[0].StartsWith("UstaStorage"))
{
//если нет такой записи, то это не те данные
return false;
}
_ustaStorages.Clear();
foreach (string data in strs)
{
string[] record = data.Split(_separatorForKeyValue,
StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
continue;
}
UstaGenericCollection<DrawningUsta, DrawningObjectUsta>
collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords,
StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawningUsta? usta =
elem?.CreateDrawningUsta(_separatorForObject, _pictureWidth, _pictureHeight);
if (usta != null)
{
int? result = collection + usta;
if (result == null || result.Value == -1)
{
return false;
}
}
}
_ustaStorages.Add(record[0], collection);
}
return true;
}
} }
} }