PIbd-14 Pruidze_I.K. LabWork06 Simple #6

Closed
Delphy wants to merge 11 commits from Lab6 into master
15 changed files with 389 additions and 47 deletions
Showing only changes of commit 86e57edbc8 - Show all commits

View File

@ -26,7 +26,7 @@ public abstract class AbstractCompany
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.SetMaxCount = GetMaxCount;
_collection.MaxCount = GetMaxCount;
}
// Перегрузка оператора сложения для класса

View File

@ -1,4 +1,5 @@
namespace ProjectCruiser.CollectionGenericObj;

namespace ProjectCruiser.CollectionGenericObj;
public class ArrayGenObj<T> : ICollectionGenObj<T>
where T : class
@ -6,8 +7,9 @@ public class ArrayGenObj<T> : ICollectionGenObj<T>
// Массив объектов, которые храним
private T?[] _collection;
public int Count => _collection.Length;
public int SetMaxCount
public int MaxCount
{
get { return _collection.Length; }
set
{
if (value > 0)
@ -18,7 +20,7 @@ public class ArrayGenObj<T> : ICollectionGenObj<T>
}
}
// public int SetMaxCount { set { if (value > 0) { _collection = new T?[value]; } } }
public CollectionType GetCollectionType => CollectionType.Array;
public ArrayGenObj()
{
@ -90,5 +92,13 @@ public class ArrayGenObj<T> : ICollectionGenObj<T>
}
return null;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; ++i)
{
yield return _collection[i];
}
}
}

View File

@ -6,7 +6,7 @@ public interface ICollectionGenObj<T> where T : class
int Count { get; }
// Установка max кол-ва элементов
int SetMaxCount { set; }
int MaxCount { set; get; }
/// Добавление объекта в коллекцию
/// <param name="obj">Добавляемый объект</param>
@ -21,4 +21,10 @@ public interface ICollectionGenObj<T> where T : class
// Получение объекта по позиции
T? GetItem(int position);
// Получение типа коллекции
CollectionType GetCollectionType { get; }
// Получение объектов коллекции по одному
IEnumerable<T?> GetItems();
}

View File

@ -14,7 +14,13 @@ public class ListGenObj<T> : ICollectionGenObj<T>
private int _maxCount;
public int Count => _collection.Count;
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } }
public int MaxCount
{
get { return _collection.Count; }
set { if (value > 0) { _maxCount = value; } }
}
public CollectionType GetCollectionType => CollectionType.List;
public ListGenObj()
{
@ -67,4 +73,12 @@ public class ListGenObj<T> : ICollectionGenObj<T>
_collection.RemoveAt(position);
return item;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Count; ++i)
{
yield return _collection[i];
}
}
}

View File

@ -1,8 +1,19 @@
namespace ProjectCruiser.CollectionGenericObj;
using System.Text;
using ProjectCruiser.DrawningSamples;
namespace ProjectCruiser.CollectionGenericObj;
public class StorageCollection<T>
where T : class
where T : DrawningBase
{
// Разделитель для записи ключа и значения элемента словаря
private readonly string _separatorForKeyValue = "|";
// Разделитель для записей коллекции данных в файл
private readonly string _separatorItems = ";";
// Ключевое слово, с которого должен начинаться файл
private readonly string _collectionKey = "CollectionsStorage";
// Словарь (хранилище) с коллекциями < name, type (class) >
readonly Dictionary<string, ICollectionGenObj<T>> _storages;
@ -14,9 +25,7 @@ where T : class
_storages = new Dictionary<string, ICollectionGenObj<T>>();
}
/// Добавление коллекции в хранилище
/// <param name="name">Название коллекции</param>
/// <param name="collectionType">тип коллекции</param>
// Добавление коллекции в хранилище
public void AddCollection(string name, CollectionType collType)
{
if (name == null || _storages.ContainsKey(name)
@ -25,27 +34,152 @@ where T : class
return;
}
ICollectionGenObj<T> collection = CreateCollection(collType);
_storages.Add(name, collection);
/*
switch (collType)
{
case CollectionType.List: _storages.Add(name, new ListGenObj<T>()); break;
// _storages[name] = new ListGenericObjects<T>(); break; [*]
case CollectionType.Array: _storages.Add(name, new ArrayGenObj<T>()); break;
}
*/
}
/// Удаление коллекции ( по ключу-строке - её имени )
/// <param name="name">Название коллекции</param>
// Удаление коллекции ( по ключу-строке - её имени )
public void DelCollection(string name)
{
if (_storages.ContainsKey(name)) _storages.Remove(name);
return;
}
/// Доступ к коллекции ( по ключу-строке - её имени )
// Доступ к коллекции ( по ключу-строке - её имени )
public ICollectionGenObj<T>? this[string name]
{
get => _storages.ContainsKey(name) ? _storages[name] : null;
}
/// Сохранение информации по автомобилям в хранилище в файл
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно,
/// false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
{
if (_storages.Count == 0) { return false; }
if (File.Exists(filename)) { File.Delete(filename); }
StringBuilder sb = new();
sb.Append(_collectionKey); // const
foreach (KeyValuePair<string, ICollectionGenObj<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(filename, FileMode.Create);
byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString());
fs.Write(info, 0, info.Length);
return true;
}
// Создание коллекции по типу
private static ICollectionGenObj<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Array => new ArrayGenObj<T>(),
CollectionType.List => new ListGenObj<T>(),
_ => null,
};
}
// Загрузка информации по кораблям в хранилище из файла
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) // >
// key | collType | maxcount | all next inf > 4
{
continue;
}
CollectionType collectionType =
(CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenObj<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?.CreateDrawningCar() is T car)
{
if (!(collection.Insert(car) == -1))
{
return false;
}
}
}
_storages.Add(record[0], collection);
}
return true;
}
}

View File

@ -14,9 +14,9 @@ public class DrawningBase
private readonly int _drawningHeight = 42; // Высота прорисовки автомобиля
// Инициализация свойств (теперь через конструктор)
public DrawningBase(int speed, double weight, Color bodyColor) : this()
public DrawningBase(EntityBase ship) : this()
{
EntityTransport = new EntityBase(speed, weight, bodyColor);
EntityTransport = ship;
}
private DrawningBase()

View File

@ -5,11 +5,9 @@ namespace ProjectCruiser.DrawningSamples;
public class DrawningCruiser : DrawningBase
{
// Инициализация свойств (все параметры класса (сущности))
public DrawningCruiser(int speed, double weight, Color bodyColor,
Color additionalColor, bool pad, bool hangars) : base(302, 42)
public DrawningCruiser(EntityCruiser ship) : base((EntityBase)ship)
{
EntityTransport = new EntityCruiser(speed, weight,
bodyColor, additionalColor, pad, hangars);
EntityTransport = ship;
}
public override void DrawTransport(Graphics g)

View File

@ -0,0 +1,41 @@
using ProjectCruiser.Entities;
namespace ProjectCruiser.DrawningSamples;
public static class ExtentionDrShip
{
// Разделитель для записи информации по объекту в файл
private static readonly string _separatorForObject = ":";
// Создание объекта из строки
public static DrawningBase? CreateDrawningCar(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityBase? ship = EntityCruiser.CreateEntity(strs);
if (ship != null)
{
return new DrawningCruiser((EntityCruiser)ship);
}
ship = EntityBase.CreateEntity(strs);
if (ship != null)
{
return new DrawningBase(ship);
}
return null;
}
// Получение данных для сохранения в файл
public static string GetDataForSave(this DrawningBase drShip)
// метод расширения за счёт ключевого слова 'this'
// вызов метода достигается не через имя класса,
// а при вызове у объекта типа DrawningBase [*]
{
string[]? array = drShip?.EntityTransport?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@ -63,12 +63,14 @@ public partial class EditorForm3 : Form
switch (e.Data?.GetData(DataFormats.Text)?.ToString())
{
case "BaseLabel":
_cruiser = new DrawningBase((int)SpeedN.Value, (double)WeightN.Value, Color.White);
EntityBase ship = new EntityBase((int)SpeedN.Value, (double)WeightN.Value, Color.White);
_cruiser = new DrawningBase(ship);
break;
case "AdvLabel":
Random rn = new Random();
_cruiser = new DrawningCruiser((int)SpeedN.Value, (double)WeightN.Value,
EntityCruiser cruiser = new EntityCruiser((int)SpeedN.Value, (double)WeightN.Value,
Color.White, Color.Black, checkBoxPads.Checked, checkBoxHangars.Checked);
_cruiser = new DrawningCruiser(cruiser);
break;
}
labelMcolor.BackColor = Color.Empty;

View File

@ -24,9 +24,26 @@ public class EntityBase
Speed = speed;
Weight = weight;
MainColor = mainc;
// Deckhouse = deckhouse;
values[0] = rn.Next(1, 4);
values[1] = rn.Next(5, 10);
values[2] = rn.Next(1, 3);
}
// Получение массива строк со значениями свойств
// объекта : тип (название класса), скорость, вес, осн. цвет [*]
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityBase), Speed.ToString(),
Weight.ToString(), MainColor.Name };
}
// decoding string to object
public static EntityBase? CreateEntity(string[] parameters)
{
if (parameters.Length != 4 || parameters.Length == 0 ||
parameters[0] != "EntityBase") return null;
return new EntityBase(Convert.ToInt32(parameters[1]),
Convert.ToDouble(parameters[2]), Color.FromName(parameters[3]));
}
}

View File

@ -21,4 +21,26 @@ public class EntityCruiser : EntityBase
HelicopterPads = pad; // non-default now for editor Form3
Hangars = hangars;
}
// Получение массива строк со значениями свойств
// объекта : тип (название класса), скорость, вес, осн. цвет [*],
// доп. цвет, истинность наличия площадки и (,) ангаров.
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityCruiser), Speed.ToString(),
Weight.ToString(), MainColor.Name, AdditionalColor.Name,
HelicopterPads.ToString(), Hangars.ToString()};
}
// decoding string to object
public static EntityCruiser? CreateEntity(string[] parameters)
{
if (parameters.Length != 7 || parameters.Length == 0 ||
parameters[0] != "EntityCruiser") return null;
return new EntityCruiser(Convert.ToInt32(parameters[1]),
Convert.ToDouble(parameters[2]), Color.FromName(parameters[3]),
Color.FromName(parameters[4]), Convert.ToBoolean(parameters[5]),
Convert.ToBoolean(parameters[6]));
}
}

View File

@ -1,4 +1,5 @@
using ProjectCruiser.DrawningSamples;
using ProjectCruiser.Entities;
using ProjectCruiser.MoveStrategy;
namespace ProjectCruiser
@ -59,16 +60,18 @@ namespace ProjectCruiser
switch (type)
{
case nameof(DrawningBase):
_drawningCruiser = new DrawningBase(random.Next(100, 300), random.Next(1000, 3000),
EntityBase ship = new EntityBase(random.Next(100, 300), random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)));
_drawningCruiser = new DrawningBase(ship);
break;
case nameof(DrawningCruiser):
_drawningCruiser = new DrawningCruiser(
EntityCruiser cruiser = new EntityCruiser(
random.Next(100, 300), random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
_drawningCruiser = new DrawningCruiser(cruiser);
break;
default:

View File

@ -46,10 +46,17 @@
btnAddCruiser = new Button();
btnCreateCompany = new Button();
pictureBox = new PictureBox();
menuStrip = new MenuStrip();
fileToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
groupBox.SuspendLayout();
companyPanel.SuspendLayout();
toolPanel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// comboBoxArrList
@ -57,7 +64,7 @@
comboBoxArrList.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
comboBoxArrList.FormattingEnabled = true;
comboBoxArrList.Items.AddRange(new object[] { "Storage" });
comboBoxArrList.Location = new Point(17, 41);
comboBoxArrList.Location = new Point(17, 51);
comboBoxArrList.Name = "comboBoxArrList";
comboBoxArrList.Size = new Size(241, 40);
comboBoxArrList.TabIndex = 0;
@ -70,9 +77,9 @@
groupBox.Controls.Add(toolPanel);
groupBox.Controls.Add(btnCreateCompany);
groupBox.Controls.Add(comboBoxArrList);
groupBox.Location = new Point(1421, 10);
groupBox.Location = new Point(1421, 47);
groupBox.Name = "groupBox";
groupBox.Size = new Size(273, 986);
groupBox.Size = new Size(273, 934);
groupBox.TabIndex = 2;
groupBox.TabStop = false;
groupBox.Text = "Tool panel";
@ -86,7 +93,7 @@
companyPanel.Controls.Add(rBtnArray);
companyPanel.Controls.Add(maskedTxtBoxCName);
companyPanel.Controls.Add(label);
companyPanel.Location = new Point(17, 91);
companyPanel.Location = new Point(17, 98);
companyPanel.Name = "companyPanel";
companyPanel.Size = new Size(243, 391);
companyPanel.TabIndex = 7;
@ -168,7 +175,7 @@
toolPanel.Controls.Add(btnDelete);
toolPanel.Controls.Add(btnAddCruiser);
toolPanel.Enabled = false;
toolPanel.Location = new Point(26, 567);
toolPanel.Location = new Point(26, 608);
toolPanel.Name = "toolPanel";
toolPanel.Size = new Size(226, 317);
toolPanel.TabIndex = 13;
@ -230,9 +237,9 @@
// btnCreateCompany
//
btnCreateCompany.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
btnCreateCompany.Location = new Point(16, 488);
btnCreateCompany.Location = new Point(16, 510);
btnCreateCompany.Name = "btnCreateCompany";
btnCreateCompany.Size = new Size(245, 73);
btnCreateCompany.Size = new Size(245, 79);
btnCreateCompany.TabIndex = 12;
btnCreateCompany.Text = "Create or switch to Company";
btnCreateCompany.UseVisualStyleBackColor = true;
@ -241,12 +248,53 @@
// pictureBox
//
pictureBox.Dock = DockStyle.Left;
pictureBox.Location = new Point(0, 0);
pictureBox.Location = new Point(0, 40);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(1415, 1007);
pictureBox.Size = new Size(1415, 967);
pictureBox.TabIndex = 3;
pictureBox.TabStop = false;
//
// menuStrip
//
menuStrip.ImageScalingSize = new Size(32, 32);
menuStrip.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(1700, 40);
menuStrip.TabIndex = 4;
menuStrip.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
fileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
fileToolStripMenuItem.Name = "fileToolStripMenuItem";
fileToolStripMenuItem.Size = new Size(71, 36);
fileToolStripMenuItem.Text = "File";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(277, 44);
saveToolStripMenuItem.Text = "Save";
saveToolStripMenuItem.Click += saveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(277, 44);
loadToolStripMenuItem.Text = "Load";
loadToolStripMenuItem.Click += loadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file|*.txt";
//
// openFileDialog
//
openFileDialog.Filter = "txt file|*.txt";
//
// ServiceForm2
//
AutoScaleDimensions = new SizeF(13F, 32F);
@ -254,6 +302,8 @@
ClientSize = new Size(1700, 1007);
Controls.Add(pictureBox);
Controls.Add(groupBox);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "ServiceForm2";
Text = "ServiceForm2";
groupBox.ResumeLayout(false);
@ -262,7 +312,10 @@
toolPanel.ResumeLayout(false);
toolPanel.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
@ -285,5 +338,11 @@
private Button btnDeleteCollection;
private Button btnCreateCompany;
private Panel toolPanel;
private MenuStrip menuStrip;
private ToolStripMenuItem fileToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
}
}

View File

@ -21,17 +21,7 @@ public partial class ServiceForm2 : Form
toolPanel.Enabled = false;
}
// Color picker (default : random)
private static Color pickColor(Random r)
{
Color cl = new Color();
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK) cl = dialog.Color;
else Color.FromArgb(r.Next(0, 256), r.Next(0, 256), r.Next(0, 256));
return cl;
}
// Color picker (default : random) <...>
// Добавление корабля
private void btnAddTransport_Click(object sender, EventArgs e)
@ -194,4 +184,41 @@ public partial class ServiceForm2 : Form
toolPanel.Enabled = true; // block of buttons at the right bottom
RefreshListBoxItems();
}
// saving to file
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.SaveData(saveFileDialog.FileName))
{
MessageBox.Show(" < Saved succesfully >",
"Result :", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("< Failed to save >", "Result :",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
// loading from file
private void loadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
{
MessageBox.Show(" < Loaded succesfully >",
"Result :", MessageBoxButtons.OK, MessageBoxIcon.Information);
RefreshListBoxItems();
}
else
{
MessageBox.Show("< Failed to load >", "Result :",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

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