Kadyrov A.F. LabWork06 #7

Closed
NAP wants to merge 1 commits from LabWork06 into LabWork05
7 changed files with 285 additions and 17 deletions
Showing only changes of commit a4098b85e9 - Show all commits

View File

@ -36,5 +36,9 @@ namespace Battleship
{
_battleship.DrawTransport(g);
}
public string GetInfo() => _battleship?.GetDataForSave();
public static IDrawningObject Create(string data) => new DrawningObjectBattleship(data.CreateDrawningBattleship());
}
}

View File

@ -0,0 +1,53 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Battleship
{
internal static class ExtentionBattleship
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public static DrawningBattleship CreateDrawningBattleship(this string info)
{
string[] strs = info.Split(_separatorForObject);
if (strs.Length == 3)
{
return new DrawningBattleship(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]));
}
if (strs.Length == 7)
{
return new DrawningGunBattleship(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="drawningCar"></param>
/// <returns></returns>
public static string GetDataForSave(this DrawningBattleship drawningBattleship)
{
var battleship = drawningBattleship.Battleship;
var str = $"{battleship.Speed}{_separatorForObject}{battleship.Weight}{_separatorForObject}{battleship.BodyColor.Name}";
if (battleship is not EntityGunBattleship gunBattleship)
{
return str;
}
return $"{str}{_separatorForObject}{gunBattleship.DopColor.Name}{_separatorForObject}{gunBattleship.CompartmentRocket}{_separatorForObject}{gunBattleship.GunTower}{_separatorForObject}{gunBattleship.SternFence}";
}
}
}

View File

@ -45,9 +45,16 @@
this.buttonRemoveBattleship = new System.Windows.Forms.Button();
this.maskedTextBoxPosition = new System.Windows.Forms.MaskedTextBox();
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.groupBoxTools.SuspendLayout();
this.groupBoxMaps.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
this.menuStrip.SuspendLayout();
this.SuspendLayout();
//
// groupBoxTools
@ -63,9 +70,9 @@
this.groupBoxTools.Controls.Add(this.buttonRemoveBattleship);
this.groupBoxTools.Controls.Add(this.maskedTextBoxPosition);
this.groupBoxTools.Dock = System.Windows.Forms.DockStyle.Right;
this.groupBoxTools.Location = new System.Drawing.Point(744, 0);
this.groupBoxTools.Location = new System.Drawing.Point(744, 24);
this.groupBoxTools.Name = "groupBoxTools";
this.groupBoxTools.Size = new System.Drawing.Size(200, 611);
this.groupBoxTools.Size = new System.Drawing.Size(200, 587);
this.groupBoxTools.TabIndex = 0;
this.groupBoxTools.TabStop = false;
this.groupBoxTools.Text = "Инструменты";
@ -142,7 +149,7 @@
//
this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDown.BackgroundImage = global::Battleship.Properties.Resources.BatteleshipDown;
this.buttonDown.Location = new System.Drawing.Point(77, 567);
this.buttonDown.Location = new System.Drawing.Point(77, 543);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(30, 30);
this.buttonDown.TabIndex = 9;
@ -153,7 +160,7 @@
//
this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonLeft.BackgroundImage = global::Battleship.Properties.Resources.BattleshipLeft;
this.buttonLeft.Location = new System.Drawing.Point(41, 567);
this.buttonLeft.Location = new System.Drawing.Point(41, 543);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(30, 30);
this.buttonLeft.TabIndex = 8;
@ -163,7 +170,7 @@
// buttonAddBattleship
//
this.buttonAddBattleship.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonAddBattleship.Location = new System.Drawing.Point(24, 350);
this.buttonAddBattleship.Location = new System.Drawing.Point(24, 326);
this.buttonAddBattleship.Name = "buttonAddBattleship";
this.buttonAddBattleship.Size = new System.Drawing.Size(164, 30);
this.buttonAddBattleship.TabIndex = 1;
@ -175,7 +182,7 @@
//
this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonUp.BackgroundImage = global::Battleship.Properties.Resources.BattleshipUp;
this.buttonUp.Location = new System.Drawing.Point(77, 531);
this.buttonUp.Location = new System.Drawing.Point(77, 507);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(30, 30);
this.buttonUp.TabIndex = 7;
@ -186,7 +193,7 @@
//
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::Battleship.Properties.Resources.BattleshipRight;
this.buttonRight.Location = new System.Drawing.Point(113, 567);
this.buttonRight.Location = new System.Drawing.Point(113, 543);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(30, 30);
this.buttonRight.TabIndex = 6;
@ -196,7 +203,7 @@
// buttonShowOnMap
//
this.buttonShowOnMap.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonShowOnMap.Location = new System.Drawing.Point(24, 486);
this.buttonShowOnMap.Location = new System.Drawing.Point(24, 462);
this.buttonShowOnMap.Name = "buttonShowOnMap";
this.buttonShowOnMap.Size = new System.Drawing.Size(164, 30);
this.buttonShowOnMap.TabIndex = 5;
@ -207,7 +214,7 @@
// buttonShowStorage
//
this.buttonShowStorage.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonShowStorage.Location = new System.Drawing.Point(24, 450);
this.buttonShowStorage.Location = new System.Drawing.Point(24, 426);
this.buttonShowStorage.Name = "buttonShowStorage";
this.buttonShowStorage.Size = new System.Drawing.Size(164, 30);
this.buttonShowStorage.TabIndex = 4;
@ -218,7 +225,7 @@
// buttonRemoveBattleship
//
this.buttonRemoveBattleship.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRemoveBattleship.Location = new System.Drawing.Point(24, 415);
this.buttonRemoveBattleship.Location = new System.Drawing.Point(24, 391);
this.buttonRemoveBattleship.Name = "buttonRemoveBattleship";
this.buttonRemoveBattleship.Size = new System.Drawing.Size(164, 29);
this.buttonRemoveBattleship.TabIndex = 3;
@ -229,7 +236,7 @@
// maskedTextBoxPosition
//
this.maskedTextBoxPosition.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.maskedTextBoxPosition.Location = new System.Drawing.Point(24, 386);
this.maskedTextBoxPosition.Location = new System.Drawing.Point(24, 362);
this.maskedTextBoxPosition.Mask = "00";
this.maskedTextBoxPosition.Name = "maskedTextBoxPosition";
this.maskedTextBoxPosition.Size = new System.Drawing.Size(164, 23);
@ -238,12 +245,52 @@
// 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(744, 611);
this.pictureBox.Size = new System.Drawing.Size(744, 587);
this.pictureBox.TabIndex = 0;
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(944, 24);
this.menuStrip.TabIndex = 1;
//
// файл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(48, 20);
this.файлToolStripMenuItem.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";
//
// FormMapWithSetBattleship
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
@ -251,6 +298,8 @@
this.ClientSize = new System.Drawing.Size(944, 611);
this.Controls.Add(this.pictureBox);
this.Controls.Add(this.groupBoxTools);
this.Controls.Add(this.menuStrip);
this.MainMenuStrip = this.menuStrip;
this.Name = "FormMapWithSetBattleship";
this.Text = "Карта с набором объектов";
this.groupBoxTools.ResumeLayout(false);
@ -258,7 +307,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();
}
@ -281,5 +333,11 @@
private ListBox listBoxMaps;
private Button buttonAddMap;
private TextBox textBoxNewMapName;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
}
}

View File

@ -178,6 +178,47 @@ namespace Battleship
{
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
/// <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))
{
ReloadMaps();
MessageBox.Show("Загрузка данных прошла успешно", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Ошибка загрузки данных", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}

View File

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

View File

@ -68,6 +68,32 @@ namespace Battleship
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 battleship in _setBattleship.GetBattleship())
{
data += $"{battleship.GetInfo()}{separatorData}";
}
return data;
}
/// <summary>
/// Загрузка списка из массива строк
/// </summary>
/// <param name="records"></param>
public void LoadData(string[] records)
{
foreach (var rec in records)
{
_setBattleship.Insert(DrawningObjectBattleship.Create(rec) as T);
}
}
public void Shaking()
{
int j = _setBattleship.Count - 1;

View File

@ -8,7 +8,7 @@ namespace Battleship
{
internal class MapsCollection
{
readonly Dictionary<string, MapWithSetBattleshipGeneric<DrawningObjectBattleship, AbstractMap>> _mapStorage;
readonly Dictionary<string, MapWithSetBattleshipGeneric<IDrawningObject, AbstractMap>> _mapStorage;
public List<string> Keys => _mapStorage.Keys.ToList();
@ -16,15 +16,23 @@ namespace Battleship
private readonly int _pictureHeight;
/// Разделитель для записи информации по элементу словаря в файл
/// </summary>
private readonly char separatorDict = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char separatorData = ';';
public MapsCollection(int pictureWidth, int pictureHeight)
{
_mapStorage = new Dictionary<string, MapWithSetBattleshipGeneric<DrawningObjectBattleship, AbstractMap>>();
_mapStorage = new Dictionary<string, MapWithSetBattleshipGeneric<IDrawningObject, AbstractMap>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
public void AddMap(string name, AbstractMap map)
{
var NewElem = new MapWithSetBattleshipGeneric<DrawningObjectBattleship, AbstractMap>(
var NewElem = new MapWithSetBattleshipGeneric<IDrawningObject, AbstractMap>(
_pictureWidth, _pictureHeight, map);
_mapStorage.Add(name, NewElem);
}
@ -32,12 +40,84 @@ namespace Battleship
{
_mapStorage.Remove(name);
}
public MapWithSetBattleshipGeneric<DrawningObjectBattleship, AbstractMap> this[string ind]
public MapWithSetBattleshipGeneric<IDrawningObject, AbstractMap> this[string ind]
{
get
{
return _mapStorage[ind];
}
}
/// <summary>
/// Метод записи информации в файл
/// </summary>
/// <param name="text">Строка, которую следует записать</param>
/// <param name="stream">Поток для записи</param>
private static void WriteToFile(string text, FileStream stream)
Review

Неиспользуемый метод

Неиспользуемый метод
{
byte[] info = new UTF8Encoding(true).GetBytes(text);
stream.Write(info, 0, info.Length);
}
/// <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 _mapStorage)
{
fs.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 fs = new(filename))
{
if (!fs.ReadLine().Contains("MapsCollection"))
Review

Файл может быть пустым и тогда возникнет ошибка

Файл может быть пустым и тогда возникнет ошибка
{
return false;
}
_mapStorage.Clear();
while (!fs.EndOfStream)
{
var elem = fs.ReadLine().Split(separatorDict);
AbstractMap map = null;
switch (elem[1])
{
case "SimpleMap":
map = new SimpleMap();
break;
case "WallMap":
map = new WaterMap();
break;
}
_mapStorage.Add(elem[0], new
MapWithSetBattleshipGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorage[elem[0]].LoadData(elem[2].Split(separatorData,
StringSplitOptions.RemoveEmptyEntries));
}
}
return true;
}
}
}