This commit is contained in:
leonteva.v 2024-05-18 17:32:59 +04:00
parent 127851efbe
commit f177ed3b2c
13 changed files with 373 additions and 35 deletions

View File

@ -51,7 +51,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

@ -17,7 +17,7 @@ namespace ProjectBattleship.CollectionGenericObjects
/// <summary> /// <summary>
/// Установка максимального количества элементов /// Установка максимального количества элементов
/// </summary> /// </summary>
int SetMaxCount { set; } int MaxCount { get; set; }
/// <summary> /// <summary>
/// Добавление объекта в коллекцию /// Добавление объекта в коллекцию
@ -38,7 +38,7 @@ namespace ProjectBattleship.CollectionGenericObjects
/// </summary> /// </summary>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns>true - удачно, false - удаление не удалось</returns> /// <returns>true - удачно, false - удаление не удалось</returns>
T? Remove(int position); T Remove(int position);
/// <summary> /// <summary>
/// Получение объекта по позиции /// Получение объекта по позиции
@ -46,5 +46,15 @@ namespace ProjectBattleship.CollectionGenericObjects
/// <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

@ -19,7 +19,18 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
/// </summary> /// </summary>
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 => _maxCount;
set
{
if (value > 0)
{
_maxCount = value;
}
}
}
public CollectionType GetCollectionType => CollectionType.List;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
@ -49,12 +60,19 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
_collection.Insert(position, obj); _collection.Insert(position, obj);
return true; return true;
} }
public T? Remove(int position) public T Remove(int position)
{ {
if (position < 0 || position >= _collection.Count) if (position < 0 || position >= _collection.Count)
return null; return null;
T? temp = _collection[position]; T temp = _collection[position];
_collection.RemoveAt(position); _collection.RemoveAt(position);
return temp; return temp;
} }
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Count; ++i)
{
yield return _collection[i];
}
}
} }

View File

@ -22,8 +22,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
/// <summary> /// <summary>
/// Установка максимального кол-ва объектов /// Установка максимального кол-ва объектов
/// </summary> /// </summary>
public int SetMaxCount public int MaxCount
{ {
get
{
return _collection.Length;
}
set set
{ {
if (value > 0) if (value > 0)
@ -39,7 +43,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
} }
} }
} }
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
@ -97,13 +101,20 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
} }
return false; return false;
} }
public T? Remove(int position) public T Remove(int position)
{ {
if (position < 0 || position >= _collection.Length || _collection[position] == null) // проверка позиции и наличия объекта if (position < 0 || position >= _collection.Length || _collection[position] == null) // проверка позиции и наличия объекта
return null; return null;
T? temp = _collection[position]; T temp = _collection[position];
_collection[position] = null; _collection[position] = null;
return temp; return temp;
} }
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)
{
yield return _collection[i];
}
}
} }

View File

@ -1,13 +1,15 @@
using ProjectBattleship.CollectionGenericObjects; using ProjectBattleship.CollectionGenericObjects;
using ProjectBattleship.Drawnings;
using System.Text;
namespace ProjectSportCar.CollectionGenericObjects; namespace ProjectBattleship.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 : DrawingShip
{ {
/// <summary> /// <summary>
/// Словарь (хранилище) с коллекциями /// Словарь (хранилище) с коллекциями
@ -20,6 +22,9 @@ public class StorageCollection<T>
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
private readonly string _collectionKey = "CollectionsStorage";
private readonly string _separatorForKeyValue = "|";
private readonly string _separatorItems = ";";
public StorageCollection() public StorageCollection()
{ {
_storages = new Dictionary<string, ICollectionGenericObjects<T>>(); _storages = new Dictionary<string, ICollectionGenericObjects<T>>();
@ -68,4 +73,98 @@ public class StorageCollection<T>
return null; return null;
} }
} }
public bool SaveData(string filename)
{
if (_storages.Count == 0)
{
return false;
}
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder sb = new();
using (StreamWriter sw = new StreamWriter(filename))
{
sw.WriteLine(_collectionKey.ToString());
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> kvpair in _storages)
{
// не сохраняем пустые коллекции
if (kvpair.Value.Count == 0)
continue;
sb.Append(kvpair.Key);
sb.Append(_separatorForKeyValue);
sb.Append(kvpair.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(kvpair.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in kvpair.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
continue;
sb.Append(data);
sb.Append(_separatorItems);
}
sw.WriteLine(sb.ToString());
sb.Clear();
}
}
return true;
}
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
}
using (StreamReader sr = new StreamReader(filename))
{
string? str;
str = sr.ReadLine();
if (str != _collectionKey.ToString())
return false;
_storages.Clear();
while ((str = sr.ReadLine()) != null)
{
string[] record = str.Split(_separatorForKeyValue);
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?.CreateDrawningShip() is T ship)
{
if (collection.Insert(ship) == -1)
return false;
}
}
_storages.Add(record[0], collection);
}
}
return true;
}
/// <summary>
/// Создание коллекции по типу
/// </summary>
/// <param name="collectionType"></param>
/// <returns></returns>
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
} }

View File

@ -3,9 +3,13 @@
namespace ProjectBattleship.Drawnings; namespace ProjectBattleship.Drawnings;
public class DrawingBattleship : DrawingShip public class DrawingBattleship : DrawingShip
{ {
public DrawingBattleship(int speed, double weight, Color bodyColor, Color additionalColor, bool turret, bool rocketLauncher) : base(150, 50) public DrawingBattleship(EntityShip ship) : base(143, 75)
{ {
EntityShip = new EntityBattleship(speed, weight, bodyColor, additionalColor, turret, rocketLauncher); EntityShip = ship;
}
public DrawingBattleship(int speed, double weight, Color bodycolor, Color additionalcolor, bool turret, bool rocketLauncher) : base(143, 75)
{
EntityShip = new EntityBattleship(speed, weight, bodycolor, additionalcolor, turret, rocketLauncher);
} }
public override void DrawTransport(Graphics g) public override void DrawTransport(Graphics g)
{ {

View File

@ -33,6 +33,10 @@ public class DrawingShip
{ {
_shipWidth = shipWidth; _shipWidth = shipWidth;
_shipHeight = shipHeight; _shipHeight = shipHeight;
}
public DrawingShip(EntityShip ship) : this()
{
EntityShip = ship;
} }
public bool SetPictureSize(int width, int height) public bool SetPictureSize(int width, int height)
{ {

View File

@ -0,0 +1,53 @@
using ProjectBattleship.Entities;
using ProjectBattleship.Drawnings;
using ProjectBattleship.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBattleship.Drawnings;
public static class ExtentionDrawingShip
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawingShip? CreateDrawningShip(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityShip? ship = EntityBattleship.CreateEntityBattleship(strs);
if (ship != null)
{
return new DrawingBattleship(ship);
}
ship = EntityShip.CreateEntityShip(strs);
if (ship != null)
{
return new DrawingShip(ship);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningShip">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawingShip drawningShip)
{
string[]? array = drawningShip?.EntityShip?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@ -1,4 +1,6 @@
namespace ProjectBattleship.Entities; using System.Net.Sockets;
namespace ProjectBattleship.Entities;
public class EntityBattleship : EntityShip public class EntityBattleship : EntityShip
{ {
public Color AdditionalColor { get; private set; } public Color AdditionalColor { get; private set; }
@ -15,4 +17,21 @@ public class EntityBattleship : EntityShip
{ {
AdditionalColor = addColor ?? AdditionalColor; AdditionalColor = addColor ?? AdditionalColor;
} }
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityBattleship), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, Turret.ToString(), RocketLauncher.ToString() };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityBattleship? CreateEntityBattleship(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntityBattleship))
{
return null;
}
return new EntityBattleship(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]));
}
} }

View File

@ -15,4 +15,22 @@ public class EntityShip
{ {
BodyColor = color ?? BodyColor; BodyColor = color ?? BodyColor;
} }
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityShip), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityShip? CreateEntityShip(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(EntityShip))
{
return null;
}
return new EntityShip(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
} }

View File

@ -46,10 +46,17 @@
labelCollectionName = new Label(); labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox(); comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox(); pictureBox = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
Tools.SuspendLayout(); Tools.SuspendLayout();
panelCompanyTools.SuspendLayout(); panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout(); panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout(); SuspendLayout();
// //
// Tools // Tools
@ -59,9 +66,9 @@
Tools.Controls.Add(panelStorage); Tools.Controls.Add(panelStorage);
Tools.Controls.Add(comboBoxSelectorCompany); Tools.Controls.Add(comboBoxSelectorCompany);
Tools.Dock = DockStyle.Right; Tools.Dock = DockStyle.Right;
Tools.Location = new Point(1605, 0); Tools.Location = new Point(1605, 40);
Tools.Name = "Tools"; Tools.Name = "Tools";
Tools.Size = new Size(488, 1236); Tools.Size = new Size(488, 1224);
Tools.TabIndex = 0; Tools.TabIndex = 0;
Tools.TabStop = false; Tools.TabStop = false;
Tools.Text = "Инструменты"; Tools.Text = "Инструменты";
@ -240,19 +247,62 @@
// pictureBox // pictureBox
// //
pictureBox.Dock = DockStyle.Fill; pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0); pictureBox.Location = new Point(0, 40);
pictureBox.Name = "pictureBox"; pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(1605, 1236); pictureBox.Size = new Size(1605, 1224);
pictureBox.TabIndex = 1; pictureBox.TabIndex = 1;
pictureBox.TabStop = false; pictureBox.TabStop = false;
// //
// menuStrip
//
menuStrip.ImageScalingSize = new Size(32, 32);
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(2093, 40);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(90, 36);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(343, 44);
saveToolStripMenuItem.Text = "Сохранить";
saveToolStripMenuItem.Click += saveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(343, 44);
loadToolStripMenuItem.Text = "Загрузить";
loadToolStripMenuItem.Click += loadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// openFileDialog
//
openFileDialog.Filter = "txt file | *.txt";
//
// FormShipCollection // FormShipCollection
// //
AutoScaleDimensions = new SizeF(13F, 32F); AutoScaleDimensions = new SizeF(13F, 32F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(2093, 1236); ClientSize = new Size(2093, 1264);
Controls.Add(pictureBox); Controls.Add(pictureBox);
Controls.Add(Tools); Controls.Add(Tools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormShipCollection"; Name = "FormShipCollection";
Text = "Коллекция кораблей"; Text = "Коллекция кораблей";
Tools.ResumeLayout(false); Tools.ResumeLayout(false);
@ -261,7 +311,10 @@
panelStorage.ResumeLayout(false); panelStorage.ResumeLayout(false);
panelStorage.PerformLayout(); panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false); ResumeLayout(false);
PerformLayout();
} }
#endregion #endregion
@ -284,5 +337,11 @@
private Button buttonCollectionAdd; private Button buttonCollectionAdd;
private Button buttonCreateCompany; private Button buttonCreateCompany;
private Panel panelCompanyTools; private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
} }
} }

View File

@ -1,16 +1,7 @@
using ProjectBattleship; using ProjectBattleship;
using ProjectBattleship.CollectionGenericObjects; using ProjectBattleship.CollectionGenericObjects;
using ProjectBattleship.Drawnings; using ProjectBattleship.Drawnings;
using ProjectSportCar.CollectionGenericObjects;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Battleship; namespace Battleship;
@ -200,6 +191,7 @@ public partial class FormShipCollection : Form
listBoxCollection.Items.Add(colName); listBoxCollection.Items.Add(colName);
} }
} }
} }
/// <summary> /// <summary>
/// Создание компании /// Создание компании
@ -231,4 +223,43 @@ public partial class FormShipCollection : 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 (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
{
RerfreshListBoxItems();
MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
} }

View File

@ -117,4 +117,16 @@
<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="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>204, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>447, 17</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>25</value>
</metadata>
</root> </root>