Лабораторная работа №6

This commit is contained in:
victinass 2024-04-15 08:55:03 +04:00
parent 5e5c8fdb19
commit 69ba7b26d6
14 changed files with 449 additions and 44 deletions

View File

@ -45,7 +45,7 @@ public abstract class AbstractCompany
_pictureWidth = picWidth; _pictureWidth = picWidth;
_pictureHeight = picHeight; _pictureHeight = picHeight;
_collection = collection; _collection = collection;
_collection.SetMaxCount = GetMaxCount; _collection.MaxCount = GetMaxCount;
} }
/// <summary> /// <summary>

View File

@ -15,7 +15,8 @@ public interface ICollectionGenericObjects<T>
/// <summary> /// <summary>
/// Установка максимального количества элементов /// Установка максимального количества элементов
/// </summary> /// </summary>
int SetMaxCount { set; } /// <returns></returns>
int MaxCount { get; set; }
/// <summary> /// <summary>
/// Добавление объекта в коллекцию /// Добавление объекта в коллекцию
@ -45,4 +46,15 @@ public interface ICollectionGenericObjects<T>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns>Объект</returns> /// <returns>Объект</returns>
T? Get(int position); T? Get(int position);
/// <summary>
/// Получение типа коллекции
/// </summary>
CollectionType GetCollectionType { get; }
/// <summary>
/// Получение объектов коллекции по одному
/// </summary>
/// <returns></returns>
IEnumerable<T> GetItems();
} }

View File

@ -11,6 +11,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
/// Список объектов, которые храним /// Список объектов, которые храним
/// </summary> /// </summary>
private readonly List<T?> _collection; private readonly List<T?> _collection;
public CollectionType GetCollectionType => CollectionType.List;
/// <summary> /// <summary>
/// Максимально допустимое число объектов в списке /// Максимально допустимое число объектов в списке
@ -18,7 +19,20 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
private int _maxCount; private int _maxCount;
public int Count => _collection.Count; public int Count => _collection.Count;
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } public int MaxCount
{
get
{
return Count;
}
set
{
if (value > 0)
{
_maxCount = value;
}
}
}
/// <summary> /// <summary>
/// Конструктор /// Конструктор
@ -73,4 +87,12 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
_collection.RemoveAt(position); _collection.RemoveAt(position);
return obj; return obj;
} }
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < Count; ++i)
{
yield return _collection[i];
}
}
} }

View File

@ -1,4 +1,5 @@
namespace Battleship.CollectionGenericObjects; 
namespace Battleship.CollectionGenericObjects;
/// <summary> /// <summary>
/// Параметризованный набор объектов /// Параметризованный набор объектов
@ -14,8 +15,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public int Count => _collection.Length; public int Count => _collection.Length;
public int SetMaxCount public int MaxCount
{ {
get
{
return _collection.Length;
}
set set
{ {
if (value > 0) if (value > 0)
@ -32,6 +37,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
} }
} }
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
@ -113,4 +120,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
_collection[position] = null; _collection[position] = null;
return obj; return obj;
} }
public IEnumerable<T> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)
{
yield return _collection[i];
}
}
} }

View File

@ -1,11 +1,14 @@
namespace Battleship.CollectionGenericObjects; using Battleship.Drawings;
using System.Text;
namespace Battleship.CollectionGenericObjects;
/// <summary> /// <summary>
/// Класс-хранилище коллекций /// Класс-хранилище коллекций
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
public class StorageCollection<T> public class StorageCollection<T>
where T : class where T : DrawingWarship
{ {
/// <summary> /// <summary>
/// Словарь (хранилище) с коллекциями /// Словарь (хранилище) с коллекциями
@ -60,7 +63,7 @@ public class StorageCollection<T>
} }
/// <summary> /// <summary>
/// Удаление коллекции /// Доступ к коллекции
/// </summary> /// </summary>
/// <param name="name"></param> /// <param name="name"></param>
/// <returns></returns> /// <returns></returns>
@ -76,4 +79,148 @@ public class StorageCollection<T>
return null; return null;
} }
} }
private readonly string _collectionKey = "CollectionsStorage";
private readonly string _separatorForKeyValue = "|";
private readonly string _separatorItems = ";";
/// <summary>
/// Сохранение информации по кораблям в хранилище в файл
/// </summary>
/// <param name="filname"></param>
/// <returns></returns>
public bool SaveData(string filname)
{
if (_storages.Count == 0)
{
return false;
}
if (File.Exists(filname))
{
File.Delete(filname);
}
if (File.Exists(filname))
{
File.Delete(filname);
}
StringBuilder sb = new();
sb.Append(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{
sb.Append(Environment.NewLine);
// не сохраняем пустые коллекции
if (value.Value.Count == 0)
{
continue;
}
sb.Append(value.Key);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
sb.Append(data);
sb.Append(_separatorItems);
}
}
using FileStream fs = new(filname, FileMode.Create);
byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString());
fs.Write(info, 0, info.Length);
return true;
}
/// <summary>
/// Загрузка информации по кораблям в хранилище из файла
/// </summary>
/// <param name="filename"></param>
/// <returns></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);
}
}
string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
return false;
}
if (!strs[0].Equals(_collectionKey))
{
//если нет такой записи, то это не те файлы
return false;
}
_storages.Clear();
foreach (string data in strs)
{
string[] record = data.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
{
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T> collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
return false;
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawingWarship() is T warship)
{
if (collection.Insert(warship) == -1)
{
return false;
}
}
}
_storages.Add(record[0], collection);
}
return true;
}
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
} }

View File

@ -16,11 +16,17 @@ public class DrawingBattleship : DrawingWarship
/// <param name="bodyDeck">Признак наличия палубы</param> /// <param name="bodyDeck">Признак наличия палубы</param>
/// <param name="compartment">Признак наличия отсека для ракет</param> /// <param name="compartment">Признак наличия отсека для ракет</param>
/// <param name="tower">Признак наличия башни</param> /// <param name="tower">Признак наличия башни</param>
public DrawingBattleship(int speed, double weight, Color bodyColor, Color additionalColor, bool bodyDeck, bool compartment, bool tower) : base(129, 80) public DrawingBattleship(int speed, double weight, Color bodyColor, bool compartment, bool tower, bool bodyDeck, Color additionalColor) : base(129, 80)
{ {
EntityWarship = new EntityBattleship(speed, weight, bodyColor, compartment, tower, bodyDeck, additionalColor); EntityWarship = new EntityBattleship(speed, weight, bodyColor, compartment, tower, bodyDeck, additionalColor);
} }
public DrawingBattleship(EntityBattleship warship) : base(129, 80)
{
EntityWarship = new EntityBattleship(warship.Speed, warship.Weight, warship.BodyColor, warship.Compartment, warship.Tower, warship.BodyDeck, warship.AdditionalColor);
}
public override void DrawTransport(Graphics g) public override void DrawTransport(Graphics g)
{ {
if (EntityWarship == null || EntityWarship is not EntityBattleship battleship || !_startPosX.HasValue || !_startPosY.HasValue) if (EntityWarship == null || EntityWarship is not EntityBattleship battleship || !_startPosX.HasValue || !_startPosY.HasValue)

View File

@ -88,8 +88,13 @@ public class DrawingWarship
/// <param name="drawingWarshipHeight">Высота прорисовки военного корабля</param> /// <param name="drawingWarshipHeight">Высота прорисовки военного корабля</param>
protected DrawingWarship(int drawingWarshipWidth, int drawingWarshipHeight) : this() protected DrawingWarship(int drawingWarshipWidth, int drawingWarshipHeight) : this()
{ {
_drawingWarshipWidth = drawingWarshipWidth; this._drawingWarshipWidth = drawingWarshipWidth;
_drawingWarshipHeight = drawingWarshipHeight; this._drawingWarshipHeight = drawingWarshipHeight;
}
public DrawingWarship(EntityWarship ship) : this()
{
EntityWarship = new EntityWarship(ship.Speed, ship.Weight, ship.BodyColor);
} }
/// <summary> /// <summary>

View File

@ -0,0 +1,53 @@
using Battleship.Entities;
namespace Battleship.Drawings;
/// <summary>
/// Расширение для класса EntityWarship
/// </summary>
public static class ExtentionDrawingWarship
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public static DrawingWarship? CreateDrawingWarship(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityWarship? warship = EntityBattleship.CreateEntityBattleship(strs);
if (warship != null)
{
return new DrawingBattleship((EntityBattleship)warship);
}
warship = EntityWarship.CreateEntityWarship(strs);
if (warship != null)
{
return new DrawingWarship(warship);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawingWarship"></param>
/// <returns></returns>
public static string GetDataForSave(this DrawingWarship drawingWarship)
{
string[]? array = drawingWarship?.EntityWarship?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@ -37,6 +37,7 @@ public class EntityBattleship : EntityWarship
{ {
AdditionalColor = color; AdditionalColor = color;
} }
/// <summary> /// <summary>
/// Перемещение линкора /// Перемещение линкора
/// </summary> /// </summary>
@ -50,12 +51,23 @@ public class EntityBattleship : EntityWarship
/// <param name="bodyColor"></param> /// <param name="bodyColor"></param>
public EntityBattleship(int speed, double weight, Color bodyColor, bool compartment, bool tower, bool bodyDeck, Color additionalColor) : base(speed, weight, bodyColor) public EntityBattleship(int speed, double weight, Color bodyColor, bool compartment, bool tower, bool bodyDeck, Color additionalColor) : base(speed, weight, bodyColor)
{ {
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
Compartment = compartment; Compartment = compartment;
Tower = tower; Tower = tower;
BodyDeck = bodyDeck; BodyDeck = bodyDeck;
AdditionalColor = additionalColor; AdditionalColor = additionalColor;
} }
/// <summary>
/// Создание продвинутого объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityBattleship? CreateEntityBattleship(string[] strs)
{
if (strs.Length != 8 || strs[0] != nameof(EntityBattleship))
{
return null;
}
return new EntityBattleship(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Convert.ToBoolean(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]), Color.FromName(strs[7]));
}
} }

View File

@ -1,10 +1,4 @@
using System; namespace Battleship.Entities;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Battleship.Entities;
/// <summary> /// <summary>
/// Класс-сущность Военный корабль /// Класс-сущность Военный корабль
/// </summary> /// </summary>
@ -22,6 +16,11 @@ public class EntityWarship
/// Основной цвет /// Основной цвет
/// </summary> /// </summary>
public Color BodyColor { get; private set; } public Color BodyColor { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
/// <param name="color"></param>
public void SetBodyColor(Color color) public void SetBodyColor(Color color)
{ {
BodyColor = color; BodyColor = color;
@ -44,4 +43,28 @@ public class EntityWarship
Weight = weight; Weight = weight;
BodyColor = bodyColor; BodyColor = bodyColor;
} }
/// <summary>
/// Получение строки с значением свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityWarship), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityWarship? CreateEntityWarship(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(EntityWarship))
{
return null;
}
return new EntityWarship(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
} }

View File

@ -46,10 +46,17 @@
textBoxCollectionName = new TextBox(); textBoxCollectionName = new TextBox();
labelCollectionName = new Label(); labelCollectionName = new Label();
pictureBox = new PictureBox(); pictureBox = new PictureBox();
menuStrip1 = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog1 = new OpenFileDialog();
groupBoxTools.SuspendLayout(); groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout(); panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout(); panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip1.SuspendLayout();
SuspendLayout(); SuspendLayout();
// //
// groupBoxTools // groupBoxTools
@ -57,9 +64,9 @@
groupBoxTools.Controls.Add(panelCompanyTools); groupBoxTools.Controls.Add(panelCompanyTools);
groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(876, 0); groupBoxTools.Location = new Point(876, 28);
groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(292, 656); groupBoxTools.Size = new Size(292, 628);
groupBoxTools.TabIndex = 0; groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false; groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты"; groupBoxTools.Text = "Инструменты";
@ -72,17 +79,17 @@
panelCompanyTools.Controls.Add(buttonGoToCheck); panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Controls.Add(buttonAddWarship); panelCompanyTools.Controls.Add(buttonAddWarship);
panelCompanyTools.Controls.Add(buttonRemoveWarship); panelCompanyTools.Controls.Add(buttonRemoveWarship);
panelCompanyTools.Location = new Point(6, 374); panelCompanyTools.Location = new Point(6, 367);
panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(283, 276); panelCompanyTools.Size = new Size(283, 255);
panelCompanyTools.TabIndex = 10; panelCompanyTools.TabIndex = 10;
// //
// buttonRefresh // buttonRefresh
// //
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(3, 228); buttonRefresh.Location = new Point(0, 214);
buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(277, 42); buttonRefresh.Size = new Size(280, 42);
buttonRefresh.TabIndex = 6; buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить"; buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true; buttonRefresh.UseVisualStyleBackColor = true;
@ -91,7 +98,7 @@
// maskedTextBox1 // maskedTextBox1
// //
maskedTextBox1.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; maskedTextBox1.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
maskedTextBox1.Location = new Point(3, 99); maskedTextBox1.Location = new Point(3, 85);
maskedTextBox1.Mask = "00"; maskedTextBox1.Mask = "00";
maskedTextBox1.Name = "maskedTextBox1"; maskedTextBox1.Name = "maskedTextBox1";
maskedTextBox1.Size = new Size(277, 27); maskedTextBox1.Size = new Size(277, 27);
@ -100,9 +107,9 @@
// buttonGoToCheck // buttonGoToCheck
// //
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(3, 180); buttonGoToCheck.Location = new Point(0, 166);
buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(277, 42); buttonGoToCheck.Size = new Size(283, 42);
buttonGoToCheck.TabIndex = 5; buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Передать на тесты"; buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true; buttonGoToCheck.UseVisualStyleBackColor = true;
@ -111,9 +118,9 @@
// buttonAddWarship // buttonAddWarship
// //
buttonAddWarship.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonAddWarship.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddWarship.Location = new Point(3, 3); buttonAddWarship.Location = new Point(0, 7);
buttonAddWarship.Name = "buttonAddWarship"; buttonAddWarship.Name = "buttonAddWarship";
buttonAddWarship.Size = new Size(277, 42); buttonAddWarship.Size = new Size(280, 42);
buttonAddWarship.TabIndex = 1; buttonAddWarship.TabIndex = 1;
buttonAddWarship.Text = "Добавление корабля"; buttonAddWarship.Text = "Добавление корабля";
buttonAddWarship.UseVisualStyleBackColor = true; buttonAddWarship.UseVisualStyleBackColor = true;
@ -122,9 +129,9 @@
// buttonRemoveWarship // buttonRemoveWarship
// //
buttonRemoveWarship.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; buttonRemoveWarship.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveWarship.Location = new Point(0, 132); buttonRemoveWarship.Location = new Point(0, 118);
buttonRemoveWarship.Name = "buttonRemoveWarship"; buttonRemoveWarship.Name = "buttonRemoveWarship";
buttonRemoveWarship.Size = new Size(280, 42); buttonRemoveWarship.Size = new Size(283, 42);
buttonRemoveWarship.TabIndex = 4; buttonRemoveWarship.TabIndex = 4;
buttonRemoveWarship.Text = "Удалить корабль"; buttonRemoveWarship.Text = "Удалить корабль";
buttonRemoveWarship.UseVisualStyleBackColor = true; buttonRemoveWarship.UseVisualStyleBackColor = true;
@ -244,12 +251,54 @@
// pictureBox // pictureBox
// //
pictureBox.Dock = DockStyle.Fill; pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0); pictureBox.Location = new Point(0, 28);
pictureBox.Name = "pictureBox"; pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(876, 656); pictureBox.Size = new Size(876, 628);
pictureBox.TabIndex = 1; pictureBox.TabIndex = 1;
pictureBox.TabStop = false; pictureBox.TabStop = false;
// //
// menuStrip1
//
menuStrip1.ImageScalingSize = new Size(20, 20);
menuStrip1.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new Size(1168, 28);
menuStrip1.TabIndex = 2;
menuStrip1.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(59, 24);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(227, 26);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(227, 26);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "text file | *.txt";
//
// openFileDialog1
//
openFileDialog1.FileName = "openFileDialog";
openFileDialog1.Filter = "text file | *.txt";
//
// FormWarshipCollection // FormWarshipCollection
// //
AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleDimensions = new SizeF(8F, 20F);
@ -257,6 +306,8 @@
ClientSize = new Size(1168, 656); ClientSize = new Size(1168, 656);
Controls.Add(pictureBox); Controls.Add(pictureBox);
Controls.Add(groupBoxTools); Controls.Add(groupBoxTools);
Controls.Add(menuStrip1);
MainMenuStrip = menuStrip1;
Name = "FormWarshipCollection"; Name = "FormWarshipCollection";
Text = "Коллекция кораблей"; Text = "Коллекция кораблей";
groupBoxTools.ResumeLayout(false); groupBoxTools.ResumeLayout(false);
@ -265,7 +316,10 @@
panelStorage.ResumeLayout(false); panelStorage.ResumeLayout(false);
panelStorage.PerformLayout(); panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
ResumeLayout(false); ResumeLayout(false);
PerformLayout();
} }
#endregion #endregion
@ -287,5 +341,11 @@
private Button buttonCreateCompany; private Button buttonCreateCompany;
private Button buttonCollectionDel; private Button buttonCollectionDel;
private Panel panelCompanyTools; private Panel panelCompanyTools;
private MenuStrip menuStrip1;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog1;
} }
} }

View File

@ -1,5 +1,6 @@
using Battleship.CollectionGenericObjects; using Battleship.CollectionGenericObjects;
using Battleship.Drawings; using Battleship.Drawings;
using System.Windows.Forms;
namespace Battleship; namespace Battleship;
@ -245,4 +246,45 @@ public partial class FormWarshipCollection : Form
panelCompanyTools.Enabled = true; panelCompanyTools.Enabled = true;
RerfreshListBoxItems(); RerfreshListBoxItems();
} }
/// <summary>
/// Обработка нажатия "Сохранить"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.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 (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog1.FileName))
{
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems();
}
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="menuStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>153, 17</value>
</metadata>
<metadata name="openFileDialog1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>318, 17</value>
</metadata>
</root> </root>

View File

@ -107,8 +107,7 @@ public partial class FormWarshipConfig : Form
_warship = new DrawingWarship((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White); _warship = new DrawingWarship((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White);
break; break;
case "labelModifiedObject": case "labelModifiedObject":
_warship = new DrawingBattleship((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White, _warship = new DrawingBattleship((int)numericUpDownSpeed.Value, (double)numericUpDownWeight.Value, Color.White, checkBoxCompartment.Checked, checkBoxTower.Checked, checkBoxBodyDeck.Checked, Color.Black);
Color.Black, checkBoxBodyDeck.Checked, checkBoxCompartment.Checked, checkBoxTower.Checked);
break; break;
} }