Compare commits

..

No commits in common. "f575f977b02a8b26ddb693ad4bd896c45764e8e7" and "f3a64bc61701e498ae839c43f7004aa201337a05" have entirely different histories.

16 changed files with 83 additions and 461 deletions

View File

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

View File

@ -1,32 +1,24 @@
 namespace ProjectCruiser.CollectionGenericObj;
namespace ProjectCruiser.CollectionGenericObj;
public class ArrayGenObj<T> : ICollectionGenObj<T> public class ArrayGenObj<T> : ICollectionGenObj<T>
where T : class where T : class
{ {
// Массив объектов, которые храним // Массив объектов, которые храним
private T?[] _collection; private T?[] _collection;
public int Count => _collection.Length;
// Максимально допустимое число объектов в массиве public int SetMaxCount
private int _maxCount;
public int Count => _collection.Count(s => s != null);
public int MaxCount
{ {
get { return _maxCount; }
set set
{ {
if (value > 0) if (value > 0)
{ {
if (_collection.Length == 0) _collection = new T?[value]; if (_collection.Length > 0) Array.Resize(ref _collection, value);
else Array.Resize(ref _collection, value); else _collection = new T?[value];
_maxCount = value;
} }
} }
} }
public CollectionType GetCollectionType => CollectionType.Array; // public int SetMaxCount { set { if (value > 0) { _collection = new T?[value]; } } }
public ArrayGenObj() public ArrayGenObj()
{ {
@ -34,6 +26,7 @@ public class ArrayGenObj<T> : ICollectionGenObj<T>
} }
// methods : // methods :
public T? GetItem(int index) public T? GetItem(int index)
{ {
if (index > Count || index < 0) if (index > Count || index < 0)
@ -45,13 +38,8 @@ public class ArrayGenObj<T> : ICollectionGenObj<T>
public int Insert(T? item) public int Insert(T? item)
{ {
if (Count >= _maxCount || item == null) // any empty place
{ for (int i = 0; i < Count; i++)
return -1;
}
// any empty place -> fill immediately
for (int i = 0; i < _collection.Length; i++)
{ {
if (_collection[i] == null) if (_collection[i] == null)
{ {
@ -59,59 +47,48 @@ public class ArrayGenObj<T> : ICollectionGenObj<T>
return i; return i;
} }
} }
return Count; return -1;
} }
public int Insert(T? item, int index) public int Insert(T? item, int index)
{ {
if (index >= _maxCount || Count >= _maxCount ||
index < 0 || _collection[index] != null
|| item == null)
{
return -1;
}
if (_collection[index] == null) if (_collection[index] == null)
{ {
_collection[index] = item; _collection[index] = item;
return index; return index;
} }
int min_diff = 100, firstNullIndex = 100; else
for (int i = 0; i < Count; i++)
{ {
if (_collection[i] == null int min_diff = 100, min_index = 100;
&& min_diff > Math.Abs(index - i))
for (int i = 0; i < Count; i++)
{ {
min_diff = Math.Abs(index - i); if (_collection[i] == null
firstNullIndex = i; && min_diff > Math.Abs(index - i))
{
min_diff = Math.Abs(index - i);
min_index = i;
}
} }
_collection[min_index] = item;
return min_index;
} }
_collection[firstNullIndex] = item; return -1;
return firstNullIndex;
} }
public T? Remove(int index) public T? Remove(int index)
{ {
if (index >= Count || index < 0) T? item;
// on the other positions items don't exist if (index < Count && index >= 0)
{ {
return null; item = _collection[index];
} _collection[index] = null;
return item;
T? item = _collection[index];
_collection[index] = null;
return item;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < MaxCount; ++i)
{
yield return _collection[i];
} }
return null;
} }
} }

View File

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

View File

@ -1,6 +1,4 @@
using System; using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection; using System.Reflection;
namespace ProjectCruiser.CollectionGenericObj; namespace ProjectCruiser.CollectionGenericObj;
@ -10,28 +8,13 @@ public class ListGenObj<T> : ICollectionGenObj<T>
where T : class where T : class
{ {
// Список объектов, которые храним // Список объектов, которые храним
private List<T?> _collection; private readonly List<T?> _collection;
// Максимально допустимое число объектов в списке // Максимально допустимое число объектов в списке
private int _maxCount; private int _maxCount;
public int Count => _collection.Count; public int Count => _collection.Count;
public int MaxCount public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } }
{
get { return _maxCount; }
set
{
if (value > 0)
{
if (_collection.Count == 0) _collection = new List<T>(value);
else _collection.Capacity = value; // instead of resizing
_maxCount = value;
}
}
}
public CollectionType GetCollectionType => CollectionType.List;
public ListGenObj() public ListGenObj()
{ {
@ -48,7 +31,7 @@ public class ListGenObj<T> : ICollectionGenObj<T>
return _collection[position]; return _collection[position];
} }
public int Insert(T? obj) public int Insert(T obj)
{ {
if (Count >= _maxCount || obj == null) if (Count >= _maxCount || obj == null)
{ {
@ -59,7 +42,7 @@ public class ListGenObj<T> : ICollectionGenObj<T>
return Count; return Count;
} }
public int Insert(T? obj, int position) public int Insert(T obj, int position)
{ {
if (position >= _maxCount || Count >= _maxCount || if (position >= _maxCount || Count >= _maxCount ||
position < 0 || _collection[position] != null position < 0 || _collection[position] != null
@ -84,12 +67,4 @@ public class ListGenObj<T> : ICollectionGenObj<T>
_collection.RemoveAt(position); _collection.RemoveAt(position);
return item; return item;
} }
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Count; ++i)
{
yield return _collection[i];
}
}
} }

View File

@ -1,19 +1,8 @@
using System.Text; namespace ProjectCruiser.CollectionGenericObj;
using ProjectCruiser.DrawningSamples;
namespace ProjectCruiser.CollectionGenericObj;
public class StorageCollection<T> public class StorageCollection<T>
where T : DrawningBase // class where T : class
{ {
// Разделитель для записи ключа и значения элемента словаря
private readonly string _separatorForKeyValue = "|";
// Разделитель для записей коллекции данных в файл
private readonly string _separatorItems = ";";
// Ключевое слово, с которого должен начинаться файл
private readonly string _collectionKey = "CollectionsStorage";
// Словарь (хранилище) с коллекциями < name, type (class) > // Словарь (хранилище) с коллекциями < name, type (class) >
readonly Dictionary<string, ICollectionGenObj<T>> _storages; readonly Dictionary<string, ICollectionGenObj<T>> _storages;
@ -25,7 +14,9 @@ public class StorageCollection<T>
_storages = new Dictionary<string, ICollectionGenObj<T>>(); _storages = new Dictionary<string, ICollectionGenObj<T>>();
} }
// Добавление коллекции в хранилище /// Добавление коллекции в хранилище
/// <param name="name">Название коллекции</param>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collType) public void AddCollection(string name, CollectionType collType)
{ {
if (name == null || _storages.ContainsKey(name) if (name == null || _storages.ContainsKey(name)
@ -34,165 +25,27 @@ public class StorageCollection<T>
return; return;
} }
ICollectionGenObj<T> collection = CreateCollection(collType); switch (collType)
_storages.Add(name, collection); {
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) public void DelCollection(string name)
{ {
if (_storages.ContainsKey(name)) _storages.Remove(name); if (_storages.ContainsKey(name)) _storages.Remove(name);
return; return;
} }
// Доступ к коллекции ( по ключу-строке - её имени ) - индексатор [!!!] /// Доступ к коллекции ( по ключу-строке - её имени )
public ICollectionGenObj<T>? this[string name] public ICollectionGenObj<T>? this[string name]
{ {
get => _storages.ContainsKey(name) ? _storages[name] : null; 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>> pair in _storages)
{
sb.Append(Environment.NewLine); // не сохраняем пустые коллекции
if (pair.Value.Count == 0) { continue; }
sb.Append(pair.Key);
sb.Append(_separatorForKeyValue);
sb.Append(pair.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(pair.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in pair.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
/*
string n = item.GetType().Name;
string data = null;
if (n != null && n == "DrawningCruiser")
{
data = ExtentionDrShip.GetDataForSave(item);
}
else if (n != null && n == "DrawningBase")
{
data = ExtentionDrShip.GetDataForSave(item);
}
*/
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;
}
string[] companies = new string[strs.Length - 1];
for (int k = 1; k < strs.Length; k++)
{
companies[k - 1] = strs[k];
}
_storages.Clear();
foreach (string data in companies)
{
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 ship)
{
if (collection.Insert(ship) == -1)
{
return false;
}
}
}
_storages.Add(record[0], collection);
}
return true;
}
} }

View File

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

View File

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

View File

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

View File

@ -24,26 +24,9 @@ public class EntityBase
Speed = speed; Speed = speed;
Weight = weight; Weight = weight;
MainColor = mainc; MainColor = mainc;
// Deckhouse = deckhouse;
values[0] = rn.Next(1, 4); values[0] = rn.Next(1, 4);
values[1] = rn.Next(5, 10); values[1] = rn.Next(5, 10);
values[2] = rn.Next(1, 3); 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,26 +21,4 @@ public class EntityCruiser : EntityBase
HelicopterPads = pad; // non-default now for editor Form3 HelicopterPads = pad; // non-default now for editor Form3
Hangars = hangars; Hangars = hangars;
} }
// Получение массива строк со значениями свойств
// объекта : тип (название класса), скорость, вес, осн. цвет [*],
// доп. цвет, истинность наличия площадки и (,) ангаров.
public override string[] GetStringRepresentation() // :O
{
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,5 +1,4 @@
using ProjectCruiser.DrawningSamples; using ProjectCruiser.DrawningSamples;
using ProjectCruiser.Entities;
using ProjectCruiser.MoveStrategy; using ProjectCruiser.MoveStrategy;
namespace ProjectCruiser namespace ProjectCruiser
@ -60,18 +59,16 @@ namespace ProjectCruiser
switch (type) switch (type)
{ {
case nameof(DrawningBase): case nameof(DrawningBase):
EntityBase ship = new EntityBase(random.Next(100, 300), random.Next(1000, 3000), _drawningCruiser = new DrawningBase(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)));
_drawningCruiser = new DrawningBase(ship);
break; break;
case nameof(DrawningCruiser): case nameof(DrawningCruiser):
EntityCruiser cruiser = new EntityCruiser( _drawningCruiser = new DrawningCruiser(
random.Next(100, 300), random.Next(1000, 3000), 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)),
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))); Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
_drawningCruiser = new DrawningCruiser(cruiser);
break; break;
default: default:

View File

@ -12,6 +12,7 @@ namespace ProjectCruiser
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new ServiceForm2()); Application.Run(new ServiceForm2());
// -> OceanForm1() inside*
} }
} }
} }

View File

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

View File

@ -21,7 +21,17 @@ public partial class ServiceForm2 : Form
toolPanel.Enabled = false; toolPanel.Enabled = false;
} }
// Color picker (default : random) <...> // 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;
}
// Добавление корабля // Добавление корабля
private void btnAddTransport_Click(object sender, EventArgs e) private void btnAddTransport_Click(object sender, EventArgs e)
@ -184,41 +194,4 @@ public partial class ServiceForm2 : Form
toolPanel.Enabled = true; // block of buttons at the right bottom toolPanel.Enabled = true; // block of buttons at the right bottom
RefreshListBoxItems(); 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,13 +117,4 @@
<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>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> </root>