Изменения формы. Изменения в MapsCollection. Использование StreamWriter и StreamReader.

This commit is contained in:
Никита Чернышов 2022-12-02 16:48:44 +04:00
parent 250685f040
commit 0a636cd3f2
7 changed files with 271 additions and 17 deletions

View File

@ -31,5 +31,7 @@ namespace AircraftCarrier
{
_warship.SetPosition(x, y, width, height);
}
public string GetInfo() => _warship?.GetDataForSave();
public static IDrawingObject Create(string data) => new DrawingObjectWarship(data.CreateDrawingWarship());
}
}

View File

@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AircraftCarrier
{
/// <summary>
/// Расширение для класса DrawingWarship
/// </summary>
internal static class ExtentionWarship
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public static DrawingWarship CreateDrawingWarship(this string info)
{
string[] strs = info.Split(_separatorForObject);
if (strs.Length == 3)
{
return new DrawingWarship(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]));
}
if (strs.Length == 7)
{
return new DrawingPlaneWarship(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]),
Color.FromName(strs[3]), Convert.ToBoolean(strs[4]),
Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]));
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawingWarship"></param>
/// <returns></returns>
public static string GetDataForSave(this DrawingWarship drawingWarship)
{
var warship = drawingWarship.Ship;
var str = $"{warship.Speed}{_separatorForObject}{warship.Weight}{_separatorForObject}{warship.BodyColor.Name}";
if (warship is not EntityPlaneWarship planeWarship)
{
return str;
}
return $"{str}{_separatorForObject}{planeWarship.DopColor.Name}{_separatorForObject}{planeWarship.BodyKit}{_separatorForObject}{planeWarship.СontrolPlace}{_separatorForObject}{planeWarship.RunWay}";
}
}
}

View File

@ -41,9 +41,16 @@
this.buttonUp = new System.Windows.Forms.Button();
this.buttonDown = new System.Windows.Forms.Button();
this.pictureBox = new System.Windows.Forms.PictureBox();
this.menuStrip = new System.Windows.Forms.MenuStrip();
this.FileToolStripMenuItem = 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.groupBoxTools.SuspendLayout();
this.groupBoxMaps.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
this.menuStrip.SuspendLayout();
this.SuspendLayout();
//
// groupBoxTools
@ -59,9 +66,9 @@
this.groupBoxTools.Controls.Add(this.buttonUp);
this.groupBoxTools.Controls.Add(this.buttonDown);
this.groupBoxTools.Dock = System.Windows.Forms.DockStyle.Right;
this.groupBoxTools.Location = new System.Drawing.Point(833, 0);
this.groupBoxTools.Location = new System.Drawing.Point(841, 24);
this.groupBoxTools.Name = "groupBoxTools";
this.groupBoxTools.Size = new System.Drawing.Size(217, 649);
this.groupBoxTools.Size = new System.Drawing.Size(217, 650);
this.groupBoxTools.TabIndex = 0;
this.groupBoxTools.TabStop = false;
this.groupBoxTools.Text = "Инструменты";
@ -132,7 +139,7 @@
//
// buttonShowOnMap
//
this.buttonShowOnMap.Location = new System.Drawing.Point(20, 516);
this.buttonShowOnMap.Location = new System.Drawing.Point(20, 489);
this.buttonShowOnMap.Name = "buttonShowOnMap";
this.buttonShowOnMap.Size = new System.Drawing.Size(180, 35);
this.buttonShowOnMap.TabIndex = 18;
@ -142,7 +149,7 @@
//
// buttonShowStorage
//
this.buttonShowStorage.Location = new System.Drawing.Point(20, 475);
this.buttonShowStorage.Location = new System.Drawing.Point(20, 448);
this.buttonShowStorage.Name = "buttonShowStorage";
this.buttonShowStorage.Size = new System.Drawing.Size(180, 35);
this.buttonShowStorage.TabIndex = 17;
@ -152,7 +159,7 @@
//
// buttonRemoveWarship
//
this.buttonRemoveWarship.Location = new System.Drawing.Point(20, 434);
this.buttonRemoveWarship.Location = new System.Drawing.Point(20, 407);
this.buttonRemoveWarship.Name = "buttonRemoveWarship";
this.buttonRemoveWarship.Size = new System.Drawing.Size(180, 35);
this.buttonRemoveWarship.TabIndex = 16;
@ -162,7 +169,7 @@
//
// maskedTextBoxPosition
//
this.maskedTextBoxPosition.Location = new System.Drawing.Point(20, 405);
this.maskedTextBoxPosition.Location = new System.Drawing.Point(20, 378);
this.maskedTextBoxPosition.Mask = "00";
this.maskedTextBoxPosition.Name = "maskedTextBoxPosition";
this.maskedTextBoxPosition.Size = new System.Drawing.Size(180, 23);
@ -171,7 +178,7 @@
//
// buttonAddWarship
//
this.buttonAddWarship.Location = new System.Drawing.Point(20, 364);
this.buttonAddWarship.Location = new System.Drawing.Point(20, 337);
this.buttonAddWarship.Name = "buttonAddWarship";
this.buttonAddWarship.Size = new System.Drawing.Size(180, 35);
this.buttonAddWarship.TabIndex = 14;
@ -184,7 +191,7 @@
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::AircraftCarrier.Properties.Resources.стрелкаright;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonRight.Location = new System.Drawing.Point(126, 609);
this.buttonRight.Location = new System.Drawing.Point(126, 610);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(30, 30);
this.buttonRight.TabIndex = 13;
@ -197,7 +204,7 @@
this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonLeft.BackgroundImage = global::AircraftCarrier.Properties.Resources.стрелка;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonLeft.Location = new System.Drawing.Point(54, 609);
this.buttonLeft.Location = new System.Drawing.Point(54, 610);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(30, 30);
this.buttonLeft.TabIndex = 12;
@ -210,7 +217,7 @@
this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonUp.BackgroundImage = global::AircraftCarrier.Properties.Resources.стрелкаtop;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonUp.Location = new System.Drawing.Point(90, 573);
this.buttonUp.Location = new System.Drawing.Point(90, 574);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(30, 30);
this.buttonUp.TabIndex = 11;
@ -223,7 +230,7 @@
this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDown.BackgroundImage = global::AircraftCarrier.Properties.Resources.стрелкаbott;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonDown.Location = new System.Drawing.Point(90, 609);
this.buttonDown.Location = new System.Drawing.Point(90, 610);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(30, 30);
this.buttonDown.TabIndex = 10;
@ -234,19 +241,61 @@
// 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(833, 649);
this.pictureBox.Size = new System.Drawing.Size(841, 650);
this.pictureBox.TabIndex = 1;
this.pictureBox.TabStop = false;
//
// menuStrip
//
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.FileToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(1058, 24);
this.menuStrip.TabIndex = 2;
//
// FileToolStripMenuItem
//
this.FileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.SaveToolStripMenuItem,
this.LoadToolStripMenuItem});
this.FileToolStripMenuItem.Name = "FileToolStripMenuItem";
this.FileToolStripMenuItem.Size = new System.Drawing.Size(48, 20);
this.FileToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(180, 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(180, 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";
//
// FormMapWithSetWarship
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1050, 649);
this.ClientSize = new System.Drawing.Size(1058, 674);
this.Controls.Add(this.pictureBox);
this.Controls.Add(this.groupBoxTools);
this.Controls.Add(this.menuStrip);
this.MainMenuStrip = this.menuStrip;
this.Name = "FormMapWithSetWarship";
this.Text = "Карта с набором объектов";
this.groupBoxTools.ResumeLayout(false);
@ -254,7 +303,10 @@
this.groupBoxMaps.ResumeLayout(false);
this.groupBoxMaps.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
@ -277,5 +329,11 @@
private Button buttonDeleteMap;
private ListBox listBoxMaps;
private TextBox textBoxNewMapName;
private MenuStrip menuStrip;
private ToolStripMenuItem FileToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
}
}

View File

@ -226,5 +226,46 @@ namespace AircraftCarrier
}
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].MoveObject(dir);
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.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 (_mapsCollection.LoadData(openFileDialog.FileName))
{
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadMaps();
}
else
{
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}

View File

@ -38,5 +38,10 @@ namespace AircraftCarrier
/// </summary>
/// <returns></returns>
(float Left, float Right, float Top, float Bottom) GetCurrentPosition();
/// <summary>
/// Получение информации по объекту
/// </summary>
/// <returns></returns>
string GetInfo();
}
}

View File

@ -115,6 +115,31 @@ namespace AircraftCarrier
return new(_pictureWidth, _pictureHeight);
}
/// <summary>
/// Получение данных в виде строки
/// </summary>
/// <param name="sep"></param>
/// <returns></returns>
public string GetData(char separatorType, char separatorData)
{
string data = $"{_map.GetType().Name}{separatorType}";
foreach (var warship in _setWarships.GetWarships())
{
data += $"{warship.GetInfo()}{separatorData}";
}
return data;
}
/// <summary>
/// Загрузка списка из массива строк
/// </summary>
/// <param name="records"></param>
public void LoadData(string[] records)
{
foreach (var rec in records)
{
_setWarships.Insert(DrawingObjectWarship.Create(rec) as T);
}
}
/// <summary>
/// "Взбалтываем" набор, чтобы все элементы оказались в начале
/// </summary>
private void Shaking()

View File

@ -11,7 +11,7 @@ namespace AircraftCarrier
/// <summary>
/// Словарь (хранилище) с картами
/// </summary>
readonly Dictionary<string, MapWithSetWarshipsGeneric<DrawingObjectWarship, AbstractMap>> _mapStorages;
readonly Dictionary<string, MapWithSetWarshipsGeneric<IDrawingObject, AbstractMap>> _mapStorages;
/// <summary>
/// Возвращение списка названий карт
/// </summary>
@ -25,13 +25,21 @@ namespace AircraftCarrier
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Разделитель для записи информации по элементу словаря в файл
/// </summary>
private readonly char separatorDict = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char separatorData = ';';
/// <summary>
/// Конструктор
/// </summary>
/// <param name="pictureWidth"></param>
/// <param name="pictureHeight"></param>
public MapsCollection(int pictureWidth, int pictureHeight)
{
_mapStorages = new Dictionary<string, MapWithSetWarshipsGeneric<DrawingObjectWarship, AbstractMap>>();
_mapStorages = new Dictionary<string, MapWithSetWarshipsGeneric<IDrawingObject, AbstractMap>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
@ -57,7 +65,7 @@ namespace AircraftCarrier
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public MapWithSetWarshipsGeneric<DrawingObjectWarship, AbstractMap> this[string ind]
public MapWithSetWarshipsGeneric<IDrawingObject, AbstractMap> this[string ind]
{
get
{
@ -65,5 +73,64 @@ namespace AircraftCarrier
return MapWithSetWarshipsGeneric;
}
}
/// <summary>
/// Сохранение информации по кораблям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns></returns>
public bool SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter sw = new(filename))
{
sw.Write($"MapsCollection{Environment.NewLine}");
foreach (var storage in _mapStorages)
{
sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}");
}
}
return true;
}
/// <summary>
/// Загрузка информации по кораблям в доках из файла
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
}
using (StreamReader sr = new(filename))
{
string str = "";
if ((str = sr.ReadLine()) == null || !str.Contains("MapsCollection"))
{
return false;
}
_mapStorages.Clear();
while ((str = sr.ReadLine()) != null)
{
var elem = str.Split(separatorDict);
AbstractMap map = null;
switch (elem[1])
{
case "Простая карта":
map = new SimpleMap();
break;
case "Морская карта":
map = new SeaMap();
break;
}
_mapStorages.Add(elem[0], new MapWithSetWarshipsGeneric<IDrawingObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
}
return true;
}
}
}
}