Merge pull request 'Agliullov D. A. Lab Work 6 Advanced' (#7) from Lab6 into Lab5

Reviewed-on: http://student.git.athene.tech/d.agliullov/ISEbd-21_Agliullov.D.A._AirBomber.Advanced/pulls/7
This commit is contained in:
Евгений Эгов 2022-11-07 11:31:37 +04:00
commit 3d006aabe8
9 changed files with 369 additions and 14 deletions

View File

@ -43,5 +43,9 @@ namespace AirBomber
/// <param name="drawningObject">The drawning object.</param>
/// <returns></returns>
public static explicit operator DrawningAirplane(DrawningObject drawningObject) => drawningObject._airplane;
public string GetInfo() => _airplane?.GetDataForSave();
public static IDrawningObject Create(string data) => new DrawningObject(data.CreateDrawningAirplane());
}
}

View File

@ -0,0 +1,66 @@
namespace AirBomber
{
/// <summary>
/// Расширение для класса DrawningAirplane
/// </summary>
internal static class ExtentionAirplane
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Получение цвета из строки 16-ричных чисел, либо из его имени
/// </summary>
/// <param name="hexOrName"></param>
/// <returns></returns>
private static Color GetColor(string hexOrName)
{
try
{
return Color.FromArgb(Convert.ToInt32(hexOrName, 16));
}
catch (Exception)
{
return Color.FromName(hexOrName);
}
}
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public static DrawningAirplane CreateDrawningAirplane(this string info)
{
string[] strs = info.Split(_separatorForObject);
if (strs.Length == 3)
{
return new DrawningAirplane(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), GetColor(strs[2]));
}
if (strs.Length == 6)
{
return new DrawningAirBomber(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), GetColor(strs[2]),
GetColor(strs[3]), Convert.ToBoolean(strs[4]),
Convert.ToBoolean(strs[5]));
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningAirplane"></param>
/// <returns></returns>
public static string GetDataForSave(this DrawningAirplane drawningAirplane)
{
var Airplane = drawningAirplane.Airplane;
var str = $"{Airplane.Speed}{_separatorForObject}{Airplane.Weight}{_separatorForObject}{Airplane.BodyColor.Name}";
if (Airplane is not EntityAirBomber AirBomber)
{
return str;
}
return $"{str}{_separatorForObject}{AirBomber.DopColor.Name}{_separatorForObject}{AirBomber.HasBombs}{_separatorForObject}{AirBomber.HasFuelTanks}";
}
}
}

View File

@ -57,6 +57,13 @@
this.buttonLeft = new System.Windows.Forms.Button();
this.buttonUp = new System.Windows.Forms.Button();
this.pictureBox = 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.SaveMapToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.groupBoxTools.SuspendLayout();
this.groupBoxMaps.SuspendLayout();
this.groupBoxGenerate.SuspendLayout();
@ -64,6 +71,7 @@
((System.ComponentModel.ISupportInitialize)(this.numericUpDownEngines)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericWeight)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
this.menuStrip.SuspendLayout();
this.SuspendLayout();
//
// comboTypeEngines
@ -94,9 +102,9 @@
this.groupBoxTools.Controls.Add(this.buttonLeft);
this.groupBoxTools.Controls.Add(this.buttonUp);
this.groupBoxTools.Dock = System.Windows.Forms.DockStyle.Right;
this.groupBoxTools.Location = new System.Drawing.Point(811, 0);
this.groupBoxTools.Location = new System.Drawing.Point(811, 24);
this.groupBoxTools.Name = "groupBoxTools";
this.groupBoxTools.Size = new System.Drawing.Size(204, 810);
this.groupBoxTools.Size = new System.Drawing.Size(204, 786);
this.groupBoxTools.TabIndex = 0;
this.groupBoxTools.TabStop = false;
this.groupBoxTools.Text = "Инструменты";
@ -325,7 +333,7 @@
this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDown.BackgroundImage = global::AirBomber.Properties.Resources.arrowDown;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonDown.Location = new System.Drawing.Point(90, 774);
this.buttonDown.Location = new System.Drawing.Point(90, 750);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(30, 30);
this.buttonDown.TabIndex = 10;
@ -337,7 +345,7 @@
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::AirBomber.Properties.Resources.arrowRight;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonRight.Location = new System.Drawing.Point(126, 774);
this.buttonRight.Location = new System.Drawing.Point(126, 750);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(30, 30);
this.buttonRight.TabIndex = 9;
@ -349,7 +357,7 @@
this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonLeft.BackgroundImage = global::AirBomber.Properties.Resources.arrowLeft;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonLeft.Location = new System.Drawing.Point(54, 774);
this.buttonLeft.Location = new System.Drawing.Point(54, 750);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(30, 30);
this.buttonLeft.TabIndex = 8;
@ -361,7 +369,7 @@
this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonUp.BackgroundImage = global::AirBomber.Properties.Resources.arrowUp;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonUp.Location = new System.Drawing.Point(90, 738);
this.buttonUp.Location = new System.Drawing.Point(90, 714);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(30, 30);
this.buttonUp.TabIndex = 7;
@ -371,12 +379,60 @@
// pictureBox
//
this.pictureBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBox.Location = new System.Drawing.Point(0, 0);
this.pictureBox.Location = new System.Drawing.Point(0, 24);
this.pictureBox.Name = "pictureBox";
this.pictureBox.Size = new System.Drawing.Size(811, 810);
this.pictureBox.Size = new System.Drawing.Size(811, 786);
this.pictureBox.TabIndex = 1;
this.pictureBox.TabStop = false;
//
// menuStrip
//
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(1015, 24);
this.menuStrip.TabIndex = 2;
//
// файлToolStripMenuItem
//
this.файлToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.SaveToolStripMenuItem,
this.SaveMapToolStripMenuItem,
this.LoadToolStripMenuItem});
this.файлToolStripMenuItem.Name = айлToolStripMenuItem";
this.файлToolStripMenuItem.Size = new System.Drawing.Size(48, 20);
this.файлToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(280, 22);
this.SaveToolStripMenuItem.Text = "Сохранение";
this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// LoadToolStripMenuItem
//
this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(280, 22);
this.LoadToolStripMenuItem.Text = "Загрузка";
this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
// openFileDialog
//
this.openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
this.saveFileDialog.Filter = "txt file | *.txt";
//
// SaveMapToolStripMenuItem
//
this.SaveMapToolStripMenuItem.Name = "SaveMapToolStripMenuItem";
this.SaveMapToolStripMenuItem.Size = new System.Drawing.Size(280, 22);
this.SaveMapToolStripMenuItem.Text = "Сохранение Выбранного хранилища";
this.SaveMapToolStripMenuItem.Click += new System.EventHandler(this.SaveMapToolStripMenuItem_Click);
//
// FormMapWithSetAirplanes
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
@ -384,6 +440,8 @@
this.ClientSize = new System.Drawing.Size(1015, 810);
this.Controls.Add(this.pictureBox);
this.Controls.Add(this.groupBoxTools);
this.Controls.Add(this.menuStrip);
this.MainMenuStrip = this.menuStrip;
this.Name = "FormMapWithSetAirplanes";
this.Text = "Генератор самолетов";
this.groupBoxTools.ResumeLayout(false);
@ -396,7 +454,10 @@
((System.ComponentModel.ISupportInitialize)(this.numericUpDownEngines)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericWeight)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
@ -431,5 +492,12 @@
private ListBox listBoxMaps;
private TextBox textBoxNewMapName;
private Button btnAddDeletedObject;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private ToolStripMenuItem SaveMapToolStripMenuItem;
}
}

View File

@ -20,7 +20,7 @@ namespace AirBomber
/// <summary>
/// Все объекты удаленные с каких либо карт
/// </summary>
private LinkedList<DrawningObject> _deletedObjects;
private LinkedList<IDrawningObject> _deletedObjects;
/// <summary>
/// Конструктор
/// </summary>
@ -304,5 +304,61 @@ namespace AirBomber
AddAirplaneInMap(form.SelectedAirplane);
}
}
/// <summary>
/// В зависимости от успешности сохранения показывает разные всплывающие окна
/// </summary>
private void ShowStatusSaveFile(bool succesfullSave)
{
if (succesfullSave)
{
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 SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
ShowStatusSaveFile(_mapsCollection.SaveData(saveFileDialog.FileName));
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.LoadData(openFileDialog.FileName))
{
MessageBox.Show("Открытие прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadMaps();
}
else
{
MessageBox.Show("Не удалось открыть", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void SaveMapToolStripMenuItem_Click(object sender, EventArgs e)
{
saveFileDialog.FileName = NameMap;
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
ShowStatusSaveFile(_mapsCollection.SaveMap(saveFileDialog.FileName, NameMap));
}
}
}
}

View File

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

View File

@ -9,7 +9,7 @@ namespace AirBomber
/// <summary>
/// Интерфейс для работы с объектом, прорисовываемым на форме
/// </summary>
internal interface IDrawningObject
public interface IDrawningObject
{
/// <summary>
/// Шаг перемещения объекта
@ -39,5 +39,11 @@ namespace AirBomber
/// </summary>
/// <returns></returns>
RectangleF GetCurrentPosition();
/// <summary>
/// Получение информации по объекту
/// </summary>
/// <returns></returns>
string GetInfo();
}
}

View File

@ -179,5 +179,36 @@ namespace AirBomber
airplane?.DrawObject(g);
}
}
public void Clear()
{
SetAirplanes.Clear();
}
/// <summary>
/// Получение данных в виде строки
/// </summary>
/// <param name="sep"></param>
/// <returns></returns>
public string GetData(char separatorType, char separatorData)
{
string data = $"{_map.GetType().Name}{separatorType}";
foreach (var airplane in SetAirplanes.GetAirplanes())
{
data += $"{airplane.GetInfo()}{separatorData}";
}
return data;
}
/// <summary>
/// Загрузка списка из массива строк
/// </summary>
/// <param name="records"></param>
public void LoadData(string[] records)
{
foreach (var rec in records)
{
SetAirplanes.Insert(DrawningObject.Create(rec) as T);
}
}
}
}

View File

@ -15,7 +15,7 @@ namespace AirBomber
/// <summary>
/// Словарь (хранилище) с картами
/// </summary>
readonly Dictionary<string, MapWithSetAirplanesGeneric<DrawningObject,
readonly Dictionary<string, MapWithSetAirplanesGeneric<IDrawningObject,
AbstractMap>> _mapStorages;
/// <summary>
/// Возвращение списка названий карт
@ -30,6 +30,14 @@ namespace AirBomber
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Разделитель для записи информации по элементу словаря в файл
/// </summary>
private readonly char separatorDict = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char separatorData = ';';
/// <summary>
/// Конструктор
/// </summary>
/// <param name="pictureWidth"></param>
@ -37,7 +45,7 @@ namespace AirBomber
public MapsCollection(int pictureWidth, int pictureHeight)
{
_mapStorages = new Dictionary<string,
MapWithSetAirplanesGeneric<DrawningObject, AbstractMap>>();
MapWithSetAirplanesGeneric<IDrawningObject, AbstractMap>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
@ -63,7 +71,7 @@ namespace AirBomber
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public MapWithSetAirplanesGeneric<DrawningObject, AbstractMap> this[string ind]
public MapWithSetAirplanesGeneric<IDrawningObject, AbstractMap> this[string ind]
{
get
{
@ -72,7 +80,7 @@ namespace AirBomber
}
}
public DrawningObject this[string ind, int indDrawningObject]
public IDrawningObject this[string ind, int indDrawningObject]
{
get
{
@ -80,5 +88,107 @@ namespace AirBomber
return mapWithSetAirplanesGeneric?.SetAirplanes[indDrawningObject];
}
}
/// <summary>
/// Сохранение информации по самолетам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns></returns>
public bool SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter fs = new(filename))
{
fs.Write($"MapsCollection{Environment.NewLine}");
foreach (var storage in _mapStorages)
{
fs.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}");
}
}
return true;
}
public bool SaveMap(string filename, string nameMap)
{
if (!_mapStorages.ContainsKey(nameMap))
{
return false;
}
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter fs = new(filename))
{
fs.Write($"Map{Environment.NewLine}");
fs.Write($"Name: {nameMap}{Environment.NewLine}");
fs.Write(_mapStorages[nameMap].GetData(separatorDict, separatorData));
}
return true;
}
private bool LoadMap(string nameMapStorage, string nameMap, string lineData)
{
AbstractMap map = null;
switch (nameMap)
{
case "SimpleMap":
map = new SimpleMap();
break;
case "WallMap":
map = new WallMap();
break;
}
if (_mapStorages.ContainsKey(nameMapStorage))
{
_mapStorages[nameMapStorage].Clear();
}
else
{
_mapStorages[nameMapStorage] = new(_pictureWidth, _pictureHeight, map);
}
_mapStorages[nameMapStorage].LoadData(lineData.Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
return true;
}
/// <summary>
/// Загрузка информации по самолетам в ангарах из файла
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
}
using (StreamReader fs = new(filename))
{
var formatData = fs.ReadLine() ?? string.Empty;
bool isNotMapsCollection = !formatData.Contains("MapsCollection");
if (formatData.Contains("Map") && isNotMapsCollection)
{
var nameMap = fs.ReadLine().Replace("Name: ", "");
var elem = fs.ReadLine().Split(separatorDict);
return LoadMap(nameMap, elem[0], elem[1]);
}
if (isNotMapsCollection)
{
//если нет такой записи, то это не те данные
return false;
}
//очищаем записи
_mapStorages.Clear();
while (!fs.EndOfStream)
{
var elem = fs.ReadLine().Split(separatorDict);
LoadMap(elem[0], elem[1], elem[2]);
}
return true;
}
}
}
}

View File

@ -109,5 +109,10 @@ namespace AirBomber
}
}
public void Clear()
{
_places.Clear();
}
}
}