3 Commits
lab03 ... lab06

Author SHA1 Message Date
kagbie3nn@mail.ru
00cde777e1 6 базовая лабораторная 2023-12-19 00:33:54 +04:00
kagbie3nn@mail.ru
028c5c7ee9 5 базовая лабораторная 2023-11-19 18:02:52 +04:00
kagbie3nn@mail.ru
398534d097 4 базовая лабораторная 2023-11-19 16:41:27 +04:00
15 changed files with 1267 additions and 101 deletions

View File

@@ -11,6 +11,10 @@ namespace ProjectWarmlyShip.DrawningObjects
// Класс, отвечающий за прорисовку и перемещение объекта-сущности // Класс, отвечающий за прорисовку и перемещение объекта-сущности
public class DrawningWarmlyShip : DrawningShip public class DrawningWarmlyShip : DrawningShip
{ {
public void setAdditionalColor(Color color)
{
(EntityShip as EntityWarmlyShip).AdditionalColor = color;
}
/// <summary> /// <summary>
/// Инициализация свойств /// Инициализация свойств
/// </summary> /// </summary>

View File

@@ -53,6 +53,7 @@ namespace ProjectWarmlyShip.DrawningObjects
public DrawningShip(int speed, double weight, Color bodyColor, int width, int height) public DrawningShip(int speed, double weight, Color bodyColor, int width, int height)
{ {
// TODO: Продумать проверки // TODO: Продумать проверки
if (width > _shipWidth && height > _shipHeight) if (width > _shipWidth && height > _shipHeight)
{ {
_pictureWidth = width; _pictureWidth = width;
@@ -73,6 +74,7 @@ namespace ProjectWarmlyShip.DrawningObjects
protected DrawningShip(int speed, double weight, Color bodyColor, int width, int height, int shipWidth, int shipHeight) protected DrawningShip(int speed, double weight, Color bodyColor, int width, int height, int shipWidth, int shipHeight)
{ {
// TODO: Продумать проверки // TODO: Продумать проверки
if (width > _shipWidth && height > _shipHeight) if (width > _shipWidth && height > _shipHeight)
{ {
_pictureWidth = width; _pictureWidth = width;
@@ -81,6 +83,8 @@ namespace ProjectWarmlyShip.DrawningObjects
_shipHeight = shipHeight; _shipHeight = shipHeight;
EntityShip = new EntityShip(speed, weight, bodyColor); EntityShip = new EntityShip(speed, weight, bodyColor);
} }
} }
/// <summary> /// <summary>
/// Установка позиции /// Установка позиции
@@ -94,10 +98,12 @@ namespace ProjectWarmlyShip.DrawningObjects
else _startPosX = 0; else _startPosX = 0;
if ((y > 0) && (y < _pictureHeight)) if ((y > 0) && (y < _pictureHeight))
_startPosY = y; _startPosY = y;
else _startPosY = 0; else _startPosY = 0;
_startPosX = x; _startPosX = x;
_startPosY = y; _startPosY = y;
} }
/// <summary> /// <summary>
/// Координата X объекта /// Координата X объекта
/// </summary> /// </summary>
@@ -114,6 +120,7 @@ namespace ProjectWarmlyShip.DrawningObjects
/// Высота объекта /// Высота объекта
/// </summary> /// </summary>
public int GetHeight => _shipHeight; public int GetHeight => _shipHeight;
/// <summary> /// <summary>
/// Проверка, что объект может переместится по указанному направлению /// Проверка, что объект может переместится по указанному направлению
/// </summary> /// </summary>
@@ -136,6 +143,7 @@ namespace ProjectWarmlyShip.DrawningObjects
//вниз //вниз
DirectionType.Down => _startPosY + _shipHeight + EntityShip.Step < _pictureHeight, DirectionType.Down => _startPosY + _shipHeight + EntityShip.Step < _pictureHeight,
}; };
} }
/// <summary> /// <summary>
/// Изменение направления перемещения /// Изменение направления перемещения
@@ -165,8 +173,10 @@ namespace ProjectWarmlyShip.DrawningObjects
case DirectionType.Down: case DirectionType.Down:
_startPosY += (int)EntityShip.Step; _startPosY += (int)EntityShip.Step;
break; break;
} }
} }
/// <summary> /// <summary>
/// Прорисовка объекта /// Прорисовка объекта
/// </summary> /// </summary>
@@ -177,6 +187,7 @@ namespace ProjectWarmlyShip.DrawningObjects
{ {
return; return;
} }
Brush BodyBrush = new SolidBrush(EntityShip.BodyColor); Brush BodyBrush = new SolidBrush(EntityShip.BodyColor);
//границы корабля //границы корабля
@@ -193,6 +204,12 @@ namespace ProjectWarmlyShip.DrawningObjects
Brush brBl = new SolidBrush(Color.LightBlue); Brush brBl = new SolidBrush(Color.LightBlue);
g.FillRectangle(brBl, _startPosX + 50, _startPosY + 0, 125, 12); g.FillRectangle(brBl, _startPosX + 50, _startPosY + 0, 125, 12);
} }
public void setBodyColor(Color color)
{
EntityShip.BodyColor = color;
}
/// <summary> /// <summary>
/// Получение объекта IMoveableObject из объекта DrawningCar /// Получение объекта IMoveableObject из объекта DrawningCar
/// </summary> /// </summary>

View File

@@ -22,7 +22,7 @@ namespace ProjectWarmlyShip.Entities
/// <summary> /// <summary>
/// Основной цвет /// Основной цвет
/// </summary> /// </summary>
public Color BodyColor { get; private set; } public Color BodyColor { get; set; }
/// <summary> /// <summary>
/// Шаг перемещения автомобиля /// Шаг перемещения автомобиля
/// </summary> /// </summary>

View File

@@ -11,7 +11,7 @@ namespace ProjectWarmlyShip.Entities
/// <summary> /// <summary>
/// Дополнительный цвет (для опциональных элементов) /// Дополнительный цвет (для опциональных элементов)
/// </summary> /// </summary>
public Color AdditionalColor { get; private set; } public Color AdditionalColor { get; set; }
/// <summary> /// <summary>
/// Признак (опция) наличия труб /// Признак (опция) наличия труб
/// </summary> /// </summary>

View File

@@ -0,0 +1,53 @@
using ProjectWarmlyShip.DrawningObjects;
using ProjectWarmlyShip.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectWarmlyShip
{
/// <summary>
/// Расширение для класса EntityShip
/// </summary>
public static class ExtentionShip
{
public static DrawningShip? CreateDrawningShip(this string info, char separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawningShip(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
}
if (strs.Length == 6)
{
return new DrawningWarmlyShip(
Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]),
Color.FromName(strs[2]),
Color.FromName(strs[3]),
Convert.ToBoolean(strs[4]),
Convert.ToBoolean(strs[5]), width, height);
}
return null;
}
public static string GetDataForSave(this DrawningShip ship, char separatorForObject)
{
var Ship = ship.EntityShip;
if (Ship == null)
{
return string.Empty;
}
var str = $"{Ship.Speed}{separatorForObject}{Ship.Weight}{separatorForObject}{Ship.BodyColor.Name}";
if (Ship is not EntityWarmlyShip warmlyShip)
{
return str;
}
return $"{str}{separatorForObject}{warmlyShip.AdditionalColor.Name}{separatorForObject}{warmlyShip.ShipPipes}{separatorForObject}{warmlyShip.ShipFuel}";
}
}
}

View File

@@ -34,16 +34,29 @@
buttonRefreshCollection = new Button(); buttonRefreshCollection = new Button();
buttonRemoveShip = new Button(); buttonRemoveShip = new Button();
ButtonAddShip = new Button(); ButtonAddShip = new Button();
groupBox2 = new GroupBox();
buttonDelObject = new Button();
listBoxStorages = new ListBox();
buttonAddObject = new Button();
textBoxStorageName = new TextBox();
файлToolStripMenuItem = new ToolStripMenuItem();
сохранениеToolStripMenuItem = new ToolStripMenuItem();
загрузкаToolStripMenuItem = new ToolStripMenuItem();
menuStrip = new MenuStrip();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
groupBox1.SuspendLayout(); groupBox1.SuspendLayout();
groupBox2.SuspendLayout();
menuStrip.SuspendLayout();
SuspendLayout(); SuspendLayout();
// //
// pictureBoxCollection // pictureBoxCollection
// //
pictureBoxCollection.Dock = DockStyle.Fill; pictureBoxCollection.Dock = DockStyle.Fill;
pictureBoxCollection.Location = new Point(0, 0); pictureBoxCollection.Location = new Point(0, 24);
pictureBoxCollection.Name = "pictureBoxCollection"; pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(800, 450); pictureBoxCollection.Size = new Size(800, 426);
pictureBoxCollection.SizeMode = PictureBoxSizeMode.AutoSize; pictureBoxCollection.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBoxCollection.TabIndex = 0; pictureBoxCollection.TabIndex = 0;
pictureBoxCollection.TabStop = false; pictureBoxCollection.TabStop = false;
@@ -63,14 +76,14 @@
// //
// maskedTextBoxNumber // maskedTextBoxNumber
// //
maskedTextBoxNumber.Location = new Point(16, 175); maskedTextBoxNumber.Location = new Point(16, 357);
maskedTextBoxNumber.Name = "maskedTextBoxNumber"; maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(136, 23); maskedTextBoxNumber.Size = new Size(136, 23);
maskedTextBoxNumber.TabIndex = 3; maskedTextBoxNumber.TabIndex = 3;
// //
// buttonRefreshCollection // buttonRefreshCollection
// //
buttonRefreshCollection.Location = new Point(16, 305); buttonRefreshCollection.Location = new Point(16, 415);
buttonRefreshCollection.Name = "buttonRefreshCollection"; buttonRefreshCollection.Name = "buttonRefreshCollection";
buttonRefreshCollection.Size = new Size(136, 23); buttonRefreshCollection.Size = new Size(136, 23);
buttonRefreshCollection.TabIndex = 2; buttonRefreshCollection.TabIndex = 2;
@@ -80,7 +93,7 @@
// //
// buttonRemoveShip // buttonRemoveShip
// //
buttonRemoveShip.Location = new Point(16, 214); buttonRemoveShip.Location = new Point(16, 386);
buttonRemoveShip.Name = "buttonRemoveShip"; buttonRemoveShip.Name = "buttonRemoveShip";
buttonRemoveShip.Size = new Size(136, 23); buttonRemoveShip.Size = new Size(136, 23);
buttonRemoveShip.TabIndex = 1; buttonRemoveShip.TabIndex = 1;
@@ -90,7 +103,7 @@
// //
// ButtonAddShip // ButtonAddShip
// //
ButtonAddShip.Location = new Point(16, 39); ButtonAddShip.Location = new Point(16, 328);
ButtonAddShip.Name = "ButtonAddShip"; ButtonAddShip.Name = "ButtonAddShip";
ButtonAddShip.Size = new Size(136, 23); ButtonAddShip.Size = new Size(136, 23);
ButtonAddShip.TabIndex = 0; ButtonAddShip.TabIndex = 0;
@@ -98,18 +111,109 @@
ButtonAddShip.UseVisualStyleBackColor = true; ButtonAddShip.UseVisualStyleBackColor = true;
ButtonAddShip.Click += ButtonAddShip_Click; ButtonAddShip.Click += ButtonAddShip_Click;
// //
// groupBox2
//
groupBox2.Controls.Add(buttonDelObject);
groupBox2.Controls.Add(listBoxStorages);
groupBox2.Controls.Add(buttonAddObject);
groupBox2.Controls.Add(textBoxStorageName);
groupBox2.Location = new Point(625, 22);
groupBox2.Name = "groupBox2";
groupBox2.Size = new Size(175, 300);
groupBox2.TabIndex = 4;
groupBox2.TabStop = false;
groupBox2.Text = "Наборы";
//
// buttonDelObject
//
buttonDelObject.Location = new Point(16, 240);
buttonDelObject.Name = "buttonDelObject";
buttonDelObject.Size = new Size(136, 23);
buttonDelObject.TabIndex = 3;
buttonDelObject.Text = "Удалить набор";
buttonDelObject.UseVisualStyleBackColor = true;
buttonDelObject.Click += ButtonDelObject_Click;
//
// listBoxStorages
//
listBoxStorages.FormattingEnabled = true;
listBoxStorages.ItemHeight = 15;
listBoxStorages.Location = new Point(16, 113);
listBoxStorages.Name = "listBoxStorages";
listBoxStorages.Size = new Size(136, 94);
listBoxStorages.TabIndex = 2;
listBoxStorages.Click += ListBoxObjects_SelectedIndexChanged;
//
// buttonAddObject
//
buttonAddObject.Location = new Point(16, 74);
buttonAddObject.Name = "buttonAddObject";
buttonAddObject.Size = new Size(136, 23);
buttonAddObject.TabIndex = 1;
buttonAddObject.Text = "Добавить набор";
buttonAddObject.UseVisualStyleBackColor = true;
buttonAddObject.Click += ButtonAddObject_Click;
//
// textBoxStorageName
//
textBoxStorageName.Location = new Point(16, 31);
textBoxStorageName.Name = "textBoxStorageName";
textBoxStorageName.Size = new Size(136, 23);
textBoxStorageName.TabIndex = 0;
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { сохранениеToolStripMenuItem, загрузкаToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(48, 20);
файлToolStripMenuItem.Text = "файл";
//
// сохранениеToolStripMenuItem
//
сохранениеToolStripMenuItem.Name = "сохранениеToolStripMenuItem";
сохранениеToolStripMenuItem.Size = new Size(180, 22);
сохранениеToolStripMenuItem.Text = "Сохранение";
сохранениеToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// загрузкаToolStripMenuItem
//
загрузкаToolStripMenuItem.Name = агрузкаToolStripMenuItem";
загрузкаToolStripMenuItem.Size = new Size(180, 22);
загрузкаToolStripMenuItem.Text = "Загрузка";
загрузкаToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// menuStrip
//
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(800, 24);
menuStrip.TabIndex = 5;
menuStrip.Text = "menuStrip1";
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog1";
//
// FormShipCollection // FormShipCollection
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450); ClientSize = new Size(800, 450);
Controls.Add(groupBox2);
Controls.Add(groupBox1); Controls.Add(groupBox1);
Controls.Add(pictureBoxCollection); Controls.Add(pictureBoxCollection);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormShipCollection"; Name = "FormShipCollection";
Text = "FormShipCollection"; Text = "FormShipCollection";
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
groupBox1.ResumeLayout(false); groupBox1.ResumeLayout(false);
groupBox1.PerformLayout(); groupBox1.PerformLayout();
groupBox2.ResumeLayout(false);
groupBox2.PerformLayout();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false); ResumeLayout(false);
PerformLayout(); PerformLayout();
} }
@@ -122,5 +226,16 @@
private Button buttonRemoveShip; private Button buttonRemoveShip;
private Button ButtonAddShip; private Button ButtonAddShip;
private MaskedTextBox maskedTextBoxNumber; private MaskedTextBox maskedTextBoxNumber;
private GroupBox groupBox2;
private Button buttonDelObject;
private ListBox listBoxStorages;
private Button buttonAddObject;
private TextBox textBoxStorageName;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem сохранениеToolStripMenuItem;
private ToolStripMenuItem загрузкаToolStripMenuItem;
private MenuStrip menuStrip;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
} }
} }

View File

@@ -15,21 +15,86 @@ using System.Windows.Forms;
namespace ProjectWarmlyShip namespace ProjectWarmlyShip
{ {
/// <summary> /// <summary>
/// Форма для работы с набором объектов класса DrawningCar /// Форма для работы с набором объектов класса DrawningShip
/// </summary> /// </summary>
public partial class FormShipCollection : Form public partial class FormShipCollection : Form
{ { /// <summary>
/// <summary>
/// Набор объектов /// Набор объектов
/// </summary> /// </summary>
private readonly ShipsGenericCollection<DrawningShip, DrawningObjectShip> _ships; private readonly ShipsGenericStorage _storage;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormShipCollection() public FormShipCollection()
{ {
InitializeComponent(); InitializeComponent();
_ships = new ShipsGenericCollection<DrawningShip, DrawningObjectShip>(pictureBoxCollection.Width, pictureBoxCollection.Height); _storage = new ShipsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
}
/// <summary>
/// Заполнение listBoxObjects
/// </summary>
private void ReloadObjects()
{
int index = listBoxStorages.SelectedIndex;
listBoxStorages.Items.Clear();
foreach (var key in _storage.Keys)
{
listBoxStorages.Items.Add(key);
}
if (listBoxStorages.Items.Count > 0 && (index == -1 || index
>= listBoxStorages.Items.Count))
{
listBoxStorages.SelectedIndex = 0;
}
else if (listBoxStorages.Items.Count > 0 && index > -1 &&
index < listBoxStorages.Items.Count)
{
listBoxStorages.SelectedIndex = index;
}
}
/// <summary>
/// Добавление набора в коллекцию
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddObject_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxStorageName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
}
/// <summary>
/// Выбор набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ListBoxObjects_SelectedIndexChanged(object sender,
EventArgs e)
{
pictureBoxCollection.Image =
_storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowShips();
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonDelObject_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
if (MessageBox.Show($"Удалить объект{listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(listBoxStorages.SelectedItem.ToString()
?? string.Empty);
ReloadObjects();
}
} }
/// <summary> /// <summary>
/// Добавление объекта в набор /// Добавление объекта в набор
@@ -38,19 +103,32 @@ namespace ProjectWarmlyShip
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonAddShip_Click(object sender, EventArgs e) private void ButtonAddShip_Click(object sender, EventArgs e)
{ {
FormWarmlyShip form = new FormWarmlyShip(); if (listBoxStorages.SelectedIndex == -1)
if (form.ShowDialog() == DialogResult.OK)
{ {
if (_ships + form.SelectedShip != -1) return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
FormShipConfig form = new FormShipConfig();
Action<DrawningShip>? ShipDelegate = new((m) =>
{
bool q = (obj + m);
if (q)
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = _ships.ShowShips(); pictureBoxCollection.Image = obj.ShowShips();
} }
else else
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show("Не удалось добавить объект");
} }
} });
form.AddEvent(ShipDelegate);
form.Show();
} }
/// <summary> /// <summary>
/// Удаление объекта из набора /// Удаление объекта из набора
@@ -59,21 +137,26 @@ namespace ProjectWarmlyShip
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonRemoveShip_Click(object sender, EventArgs e) private void ButtonRemoveShip_Click(object sender, EventArgs e)
{ {
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{ {
return; return;
} }
int pos = -1; int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
try if (obj - pos != null)
{
pos = Convert.ToInt32(maskedTextBoxNumber.Text);
}
catch (Exception ex) { }
if (_ships - pos)
{ {
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
pictureBoxCollection.Image = _ships.ShowShips(); pictureBoxCollection.Image = obj.ShowShips();
} }
else else
{ {
@@ -87,8 +170,59 @@ namespace ProjectWarmlyShip
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonRefreshCollection_Click(object sender, EventArgs e) private void ButtonRefreshCollection_Click(object sender, EventArgs e)
{ {
pictureBoxCollection.Image = _ships.ShowShips(); if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
pictureBoxCollection.Image = obj.ShowShips();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.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)
{
// TODO продумать логику
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.LoadData(openFileDialog.FileName))
{
ReloadObjects();
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
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="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>126, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>261, 17</value>
</metadata>
</root> </root>

View File

@@ -0,0 +1,356 @@
namespace ProjectWarmlyShip
{
partial class FormShipConfig
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
groupBox1 = new GroupBox();
labelModifiedObject = new Label();
labelSimpleObject = new Label();
groupBox2 = new GroupBox();
panelWhite = new Panel();
panelYellow = new Panel();
panelBlack = new Panel();
panelGray = new Panel();
panelBlue = new Panel();
panelPurple = new Panel();
panelGreen = new Panel();
panelRed = new Panel();
checkBoxFuel = new CheckBox();
checkBoxPipes = new CheckBox();
numericUpDownWeight = new NumericUpDown();
numericUpDownSpeed = new NumericUpDown();
label2 = new Label();
label1 = new Label();
panelReciever = new Panel();
pictureBoxObject = new PictureBox();
labelAdditionalColor = new Label();
labelColor = new Label();
buttonAddObj = new Button();
buttonCancelObj = new Button();
groupBox1.SuspendLayout();
groupBox2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
panelReciever.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
SuspendLayout();
//
// groupBox1
//
groupBox1.Controls.Add(labelModifiedObject);
groupBox1.Controls.Add(labelSimpleObject);
groupBox1.Controls.Add(groupBox2);
groupBox1.Controls.Add(checkBoxFuel);
groupBox1.Controls.Add(checkBoxPipes);
groupBox1.Controls.Add(numericUpDownWeight);
groupBox1.Controls.Add(numericUpDownSpeed);
groupBox1.Controls.Add(label2);
groupBox1.Controls.Add(label1);
groupBox1.Location = new Point(12, 12);
groupBox1.Name = "groupBox1";
groupBox1.Size = new Size(459, 207);
groupBox1.TabIndex = 0;
groupBox1.TabStop = false;
groupBox1.Text = "Параметры";
//
// labelModifiedObject
//
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.Location = new Point(352, 154);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(89, 34);
labelModifiedObject.TabIndex = 8;
labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
labelModifiedObject.MouseDown += LabelObject_MouseDown;
//
// labelSimpleObject
//
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Location = new Point(244, 154);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(96, 34);
labelSimpleObject.TabIndex = 7;
labelSimpleObject.Text = "Простой";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
labelSimpleObject.MouseDown += LabelObject_MouseDown;
//
// groupBox2
//
groupBox2.Controls.Add(panelWhite);
groupBox2.Controls.Add(panelYellow);
groupBox2.Controls.Add(panelBlack);
groupBox2.Controls.Add(panelGray);
groupBox2.Controls.Add(panelBlue);
groupBox2.Controls.Add(panelPurple);
groupBox2.Controls.Add(panelGreen);
groupBox2.Controls.Add(panelRed);
groupBox2.Location = new Point(244, 33);
groupBox2.Name = "groupBox2";
groupBox2.Size = new Size(203, 100);
groupBox2.TabIndex = 6;
groupBox2.TabStop = false;
groupBox2.Text = "Цвета";
//
// panelWhite
//
panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(167, 58);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(30, 30);
panelWhite.TabIndex = 7;
//
// panelYellow
//
panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(167, 22);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(30, 30);
panelYellow.TabIndex = 3;
//
// panelBlack
//
panelBlack.BackColor = Color.Black;
panelBlack.Location = new Point(114, 58);
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(30, 30);
panelBlack.TabIndex = 6;
//
// panelGray
//
panelGray.BackColor = Color.FromArgb(64, 64, 64);
panelGray.Location = new Point(56, 58);
panelGray.Name = "panelGray";
panelGray.Size = new Size(30, 30);
panelGray.TabIndex = 5;
//
// panelBlue
//
panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(114, 22);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(30, 30);
panelBlue.TabIndex = 2;
//
// panelPurple
//
panelPurple.BackColor = Color.Purple;
panelPurple.Location = new Point(6, 58);
panelPurple.Name = "panelPurple";
panelPurple.Size = new Size(30, 30);
panelPurple.TabIndex = 4;
//
// panelGreen
//
panelGreen.BackColor = Color.Green;
panelGreen.Location = new Point(56, 22);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(30, 30);
panelGreen.TabIndex = 1;
//
// panelRed
//
panelRed.BackColor = Color.Red;
panelRed.Location = new Point(6, 22);
panelRed.Name = "panelRed";
panelRed.Size = new Size(30, 30);
panelRed.TabIndex = 0;
//
// checkBoxFuel
//
checkBoxFuel.AutoSize = true;
checkBoxFuel.Location = new Point(19, 153);
checkBoxFuel.Name = "checkBoxFuel";
checkBoxFuel.Size = new Size(222, 19);
checkBoxFuel.TabIndex = 5;
checkBoxFuel.Text = "Признак наличия топливных баков";
checkBoxFuel.UseVisualStyleBackColor = true;
//
// checkBoxPipes
//
checkBoxPipes.AutoSize = true;
checkBoxPipes.Location = new Point(19, 128);
checkBoxPipes.Name = "checkBoxPipes";
checkBoxPipes.Size = new Size(151, 19);
checkBoxPipes.TabIndex = 4;
checkBoxPipes.Text = "Признак наличия труб";
checkBoxPipes.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(74, 76);
numericUpDownWeight.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownWeight.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownWeight.Name = "numericUpDownWeight";
numericUpDownWeight.Size = new Size(61, 23);
numericUpDownWeight.TabIndex = 3;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(74, 36);
numericUpDownSpeed.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownSpeed.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownSpeed.Name = "numericUpDownSpeed";
numericUpDownSpeed.Size = new Size(61, 23);
numericUpDownSpeed.TabIndex = 2;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(6, 78);
label2.Name = "label2";
label2.Size = new Size(29, 15);
label2.TabIndex = 1;
label2.Text = "Вес:";
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(6, 38);
label1.Name = "label1";
label1.Size = new Size(62, 15);
label1.TabIndex = 0;
label1.Text = "Скорость:";
//
// panelReciever
//
panelReciever.AllowDrop = true;
panelReciever.Controls.Add(pictureBoxObject);
panelReciever.Controls.Add(labelAdditionalColor);
panelReciever.Controls.Add(labelColor);
panelReciever.Location = new Point(489, 12);
panelReciever.Name = "panelReciever";
panelReciever.Size = new Size(278, 169);
panelReciever.TabIndex = 1;
panelReciever.DragDrop += PanelObject_DragDrop;
panelReciever.DragEnter += PanelObject_DragEnter;
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(3, 34);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(272, 132);
pictureBoxObject.TabIndex = 2;
pictureBoxObject.TabStop = false;
//
// labelAdditionalColor
//
labelAdditionalColor.AllowDrop = true;
labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
labelAdditionalColor.Location = new Point(157, 11);
labelAdditionalColor.Name = "labelAdditionalColor";
labelAdditionalColor.Size = new Size(100, 20);
labelAdditionalColor.TabIndex = 1;
labelAdditionalColor.Text = "Доп. цвет";
labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter;
labelAdditionalColor.DragDrop += labelColor_DragDrop;
labelAdditionalColor.DragEnter += labelColor_DragEnter;
//
// labelColor
//
labelColor.AllowDrop = true;
labelColor.BorderStyle = BorderStyle.FixedSingle;
labelColor.Location = new Point(16, 11);
labelColor.Name = "labelColor";
labelColor.Size = new Size(100, 20);
labelColor.TabIndex = 0;
labelColor.Text = "Цвет";
labelColor.TextAlign = ContentAlignment.MiddleCenter;
labelColor.DragDrop += labelColor_DragDrop;
labelColor.DragEnter += labelColor_DragEnter;
//
// buttonAddObj
//
buttonAddObj.Location = new Point(505, 196);
buttonAddObj.Name = "buttonAddObj";
buttonAddObj.Size = new Size(100, 23);
buttonAddObj.TabIndex = 2;
buttonAddObj.Text = "Добавить";
buttonAddObj.UseVisualStyleBackColor = true;
buttonAddObj.Click += ButtonOk_Click;
//
// buttonCancelObj
//
buttonCancelObj.Location = new Point(646, 196);
buttonCancelObj.Name = "buttonCancelObj";
buttonCancelObj.Size = new Size(100, 23);
buttonCancelObj.TabIndex = 3;
buttonCancelObj.Text = "Отмена";
buttonCancelObj.UseVisualStyleBackColor = true;
//
// FormShipConfig
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 231);
Controls.Add(buttonCancelObj);
Controls.Add(buttonAddObj);
Controls.Add(panelReciever);
Controls.Add(groupBox1);
Name = "FormShipConfig";
Text = "Создание объекта";
groupBox1.ResumeLayout(false);
groupBox1.PerformLayout();
groupBox2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).EndInit();
panelReciever.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)pictureBoxObject).EndInit();
ResumeLayout(false);
}
#endregion
private GroupBox groupBox1;
private NumericUpDown numericUpDownWeight;
private NumericUpDown numericUpDownSpeed;
private Label label2;
private Label label1;
private GroupBox groupBox2;
private Panel panelRed;
private CheckBox checkBoxFuel;
private CheckBox checkBoxPipes;
private Panel panelWhite;
private Panel panelYellow;
private Panel panelBlack;
private Panel panelGray;
private Panel panelBlue;
private Panel panelPurple;
private Panel panelGreen;
private Panel panelReciever;
private Label labelColor;
private Label labelModifiedObject;
private Label labelSimpleObject;
private PictureBox pictureBoxObject;
private Label labelAdditionalColor;
private Button buttonAddObj;
private Button buttonCancelObj;
}
}

View File

@@ -0,0 +1,169 @@
using ProjectWarmlyShip.DrawningObjects;
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 ProjectWarmlyShip
{
/// <summary>
/// Форма создания объекта
/// </summary>
public partial class FormShipConfig : Form
{
/// <summary>
/// Переменная-выбранная машина
/// </summary>
DrawningShip? _ship = null;
/// <summary>
/// Событие
/// </summary>
private event Action<DrawningShip>? EventAddShip;
/// <summary>
/// Конструктор
/// </summary>
public FormShipConfig()
{
InitializeComponent();
buttonCancelObj.Click += (s, e) => Close();
panelBlack.MouseDown += PanelColor_MouseDown;
panelPurple.MouseDown += PanelColor_MouseDown;
panelGray.MouseDown += PanelColor_MouseDown;
panelGreen.MouseDown += PanelColor_MouseDown;
panelRed.MouseDown += PanelColor_MouseDown;
panelWhite.MouseDown += PanelColor_MouseDown;
panelYellow.MouseDown += PanelColor_MouseDown;
panelBlue.MouseDown += PanelColor_MouseDown;
// TODO buttonCancel.Click with lambda
}
/// <summary>
/// Отрисовать корабль
/// </summary>
private void DrawShip()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_ship?.SetPosition(5, 5);
_ship?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
/// <summary>
/// Добавление события
/// </summary>
/// <param name="ev">Привязанный метод</param>
public void AddEvent(Action<DrawningShip> ev)
{
if (EventAddShip == null)
{
EventAddShip = ev;
}
else
{
EventAddShip += ev;
}
}
/// <summary>
/// Передаем информацию при нажатии на Label
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label)?.DoDragDrop((sender as Label)?.Name,
DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(DataFormats.Text) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
/// <summary>
/// Действия при приеме перетаскиваемой информации
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragDrop(object sender, DragEventArgs e)
{
switch (e.Data?.GetData(DataFormats.Text).ToString())
{
case "labelSimpleObject":
_ship = new DrawningShip((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, pictureBoxObject.Width,
pictureBoxObject.Height);
break;
case "labelModifiedObject":
_ship = new DrawningWarmlyShip((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, Color.Black, checkBoxPipes.Checked,
checkBoxFuel.Checked, pictureBoxObject.Width,
pictureBoxObject.Height);
break;
}
DrawShip();
}
private void PanelColor_MouseDown(object sender, MouseEventArgs e)
{
(sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor,
DragDropEffects.Move | DragDropEffects.Copy);
}
// TODO Реализовать логику смены цветов: основного и дополнительного (для продвинутого объекта)
private void labelColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void labelColor_DragDrop(object sender, DragEventArgs e)
{
if (_ship == null)
return;
((Label)sender).BackColor = (Color)e.Data.GetData(typeof(Color));
switch (((Label)sender).Name)
{
case "labelColor":
_ship.setBodyColor((Color)e.Data.GetData(typeof(Color)));
break;
case "labelAdditionalColor":
if (!(_ship is DrawningWarmlyShip))
return;
(_ship as DrawningWarmlyShip).setAdditionalColor((Color)e.Data.GetData(typeof(Color)));
break;
}
DrawShip();
}
/// <summary>
/// Добавление корабля
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonOk_Click(object sender, EventArgs e)
{
EventAddShip?.Invoke(_ship);
Close();
}
}
}

View File

@@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@@ -1,11 +1,13 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Numerics;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace ProjectWarmlyShip.Generics namespace ProjectWarmlyShip.Generics
{/// <summary> {
/// <summary>
/// Параметризованный набор объектов /// Параметризованный набор объектов
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
@@ -15,44 +17,32 @@ namespace ProjectWarmlyShip.Generics
/// <summary> /// <summary>
/// Массив объектов, которые храним /// Массив объектов, которые храним
/// </summary> /// </summary>
private readonly T?[] _places; private readonly List<T?> _places;
/// <summary> /// <summary>
/// Количество объектов в массиве /// Количество объектов в массиве
/// </summary> /// </summary>
public int Count => _places.Length; public int Count => _places.Count;
/// <summary>
/// Максимальное количество объектов в списке
/// </summary>
private readonly int _maxCount;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
/// <param name="count"></param> /// <param name="count"></param>
public SetGeneric(int count) public SetGeneric(int count)
{ {
_places = new T?[count]; _maxCount = count;
_places = new List<T?>(count);
} }
/// <summary> /// <summary>
/// Добавление объекта в набор /// Добавление объекта в набор
/// </summary> /// </summary>
/// <param name="ship">Добавляемый корабль</param> /// <param name="ship">Добавляемый корабль</param>
/// <returns></returns> /// <returns></returns>
public int Insert(T ship) public bool Insert(T ship)
{ {
int index = -1; return Insert(ship, 0);
for (int i = 0; i < _places.Length; i++)
{
if (_places[i] == null)
{
index = i; break;
}
}
if (index < 0)
{
return -1;
}
for (int i = index; i > 0; i--)
{
_places[i] = _places[i - 1];
}
_places[0] = ship;
return 0;
} }
/// <summary> /// <summary>
/// Добавление объекта в набор на конкретную позицию /// Добавление объекта в набор на конкретную позицию
@@ -60,31 +50,16 @@ namespace ProjectWarmlyShip.Generics
/// <param name="ship">Добавляемый корабль</param> /// <param name="ship">Добавляемый корабль</param>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns></returns> /// <returns></returns>
public int Insert(T plane, int position) public bool Insert(T ship, int position)
{ {
if (position < 0 || position >= Count) if (position < 0 || position >= _maxCount)
return -1; return false;
if (_places[position] == null)
{ if (Count >= _maxCount)
_places[position] = plane; return false;
return position; _places.Insert(0, ship);
} return true;
int index = -1;
for (int i = position; i < Count; i++)
{
if (_places[i] == null)
{
index = i; break;
}
}
if (index < 0)
return -1;
for (int i = index; index > position; i--)
{
_places[i] = _places[i - 1];
}
_places[position] = plane;
return position;
} }
/// <summary> /// <summary>
/// Удаление объекта из набора с конкретной позиции /// Удаление объекта из набора с конкретной позиции
@@ -93,23 +68,48 @@ namespace ProjectWarmlyShip.Generics
/// <returns></returns> /// <returns></returns>
public bool Remove(int position) public bool Remove(int position)
{ {
if (position < 0 || position >= _places.Length) if (position < 0 || position > _maxCount)
return false; return false;
_places[position] = null; if (position >= Count)
return false;
_places.RemoveAt(position);
return true; return true;
} }
/// <summary> /// <summary>
/// Получение объекта из набора по позиции /// Получение объекта из набора по позиции
/// </summary> /// </summary>
/// <param name="position"></param> /// <param name="position"></param>
/// <returns></returns> /// <returns></returns>
public T? Get(int position) public T? this[int position]
{ {
if (position < 0 || position >= _places.Length) get
{
if (position < 0 || position > _maxCount)
return null; return null;
return _places[position]; return _places[position];
} }
set
{
if (position < 0 || position > _maxCount)
return;
_places[position] = value;
}
}
/// <summary>
/// Проход по списку
/// </summary>
/// <returns></returns>
public IEnumerable<T?> GetShips(int? maxShips = null)
{
for (int i = 0; i < _places.Count; ++i)
{
yield return _places[i];
if (maxShips.HasValue && i == maxShips.Value)
{
yield break;
}
}
}
} }
} }

View File

@@ -0,0 +1,16 @@
using ProjectWarmlyShip.DrawningObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectWarmlyShip
{
/// <summary>
/// Делегат для передачи объекта-самолета
/// </summary>
/// <param name="ship"></param>
public delegate void ShipDelegate(DrawningShip ship);
}

View File

@@ -42,6 +42,7 @@ namespace ProjectWarmlyShip.Generics
/// </summary> /// </summary>
/// <param name="picWidth"></param> /// <param name="picWidth"></param>
/// <param name="picHeight"></param> /// <param name="picHeight"></param>
public IEnumerable<T?> GetShips => _collection.GetShips();
public ShipsGenericCollection(int picWidth, int picHeight) public ShipsGenericCollection(int picWidth, int picHeight)
{ {
int width = picWidth / _placeSizeWidth; int width = picWidth / _placeSizeWidth;
@@ -56,13 +57,13 @@ namespace ProjectWarmlyShip.Generics
/// <param name="collect"></param> /// <param name="collect"></param>
/// <param name="obj"></param> /// <param name="obj"></param>
/// <returns></returns> /// <returns></returns>
public static int? operator +(ShipsGenericCollection<T, U> collect, T? obj) public static bool operator +(ShipsGenericCollection<T, U> collect, T? obj)
{ {
if (obj == null) if (obj == null)
{ {
return -1; return false;
} }
return collect?._collection.Insert(obj); return (bool)collect?._collection.Insert(obj);
} }
/// <summary> /// <summary>
/// Перегрузка оператора вычитания /// Перегрузка оператора вычитания
@@ -70,15 +71,14 @@ namespace ProjectWarmlyShip.Generics
/// <param name="collect"></param> /// <param name="collect"></param>
/// <param name="pos"></param> /// <param name="pos"></param>
/// <returns></returns> /// <returns></returns>
public static bool operator -(ShipsGenericCollection<T, U> collect, int public static T? operator -(ShipsGenericCollection<T, U> collect, int pos)
pos)
{ {
T? obj = collect._collection.Get(pos); T? obj = collect._collection[pos];
if (obj == null) if (obj != null)
{ {
return false; collect._collection.Remove(pos);
} }
return collect._collection.Remove(pos); return obj;
} }
/// <summary> /// <summary>
/// Получение объекта IMoveableObject /// Получение объекта IMoveableObject
@@ -87,7 +87,7 @@ namespace ProjectWarmlyShip.Generics
/// <returns></returns> /// <returns></returns>
public U? GetU(int pos) public U? GetU(int pos)
{ {
return (U?)_collection.Get(pos)?.GetMoveableObject; return (U?)_collection[pos]?.GetMoveableObject;
} }
/// <summary> /// <summary>
/// Вывод всего набора объектов /// Вывод всего набора объектов
@@ -132,7 +132,7 @@ namespace ProjectWarmlyShip.Generics
for (int i = 0; i < _collection.Count; i++) for (int i = 0; i < _collection.Count; i++)
{ {
// TODO получение объекта // TODO получение объекта
DrawningShip? Ship = _collection.Get(i); DrawningShip? Ship = _collection[i];
if (Ship == null) if (Ship == null)
continue; continue;
int r = i / width; int r = i / width;

View File

@@ -0,0 +1,173 @@
using ProjectWarmlyShip.DrawningObjects;
using ProjectWarmlyShip.Generics;
using ProjectWarmlyShip.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectWarmlyShip
{
/// <summary>
/// Класс для хранения коллекции
/// </summary>
internal class ShipsGenericStorage
{
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<string, ShipsGenericCollection<DrawningShip, DrawningObjectShip>> _shipStorages;
/// <summary>
/// Возвращение списка названий наборов
/// </summary>
public List<string> Keys => _shipStorages.Keys.ToList();
/// <summary>
/// Ширина окна отрисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна отрисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private static readonly char _separatorForKeyValue = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char _separatorRecords = ';';
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Конструктор
/// </summary>
/// <param name="pictureWidth"></param>
/// /// <param name="pictureHeight"></param>
public ShipsGenericStorage(int pictureWidth, int pictureHeight)
{
_shipStorages = new Dictionary<string, ShipsGenericCollection<DrawningShip, DrawningObjectShip>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
/// <summary>
/// Добавление набора
/// </summary>
/// <param name="name">Название набора</param>
public void AddSet(string name)
{
// TODO Прописать логику для добавления
if (_shipStorages.ContainsKey(name)) return;
_shipStorages[name] = new ShipsGenericCollection<DrawningShip, DrawningObjectShip>(_pictureWidth, _pictureHeight);
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="name">Название набора</param>
public void DelSet(string name)
{
// TODO Прописать логику для удаления
if (!_shipStorages.ContainsKey(name)) return;
_shipStorages.Remove(name);
}
/// <summary>
/// Доступ к набору
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public ShipsGenericCollection<DrawningShip, DrawningObjectShip>?
this[string ind]
{
get
{
// TODO Продумать логику получения набора
if (_shipStorages.ContainsKey(ind)) return _shipStorages[ind];
return null;
}
}
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string,
ShipsGenericCollection<DrawningShip, DrawningObjectShip>> record in _shipStorages)
{
StringBuilder records = new();
foreach (DrawningShip? elem in record.Value.GetShips)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
return false;
}
using (StreamWriter writer = new StreamWriter(filename, false))
{
writer.WriteLine("ShipStorage");
writer.Write(data.ToString());
}
return true;
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
}
using (StreamReader reader = new StreamReader(filename))
{
string cheker = reader.ReadLine();
if (cheker == null)
{
return false;
}
if (!cheker.StartsWith("ShipStorage"))
{
return false;
}
_shipStorages.Clear();
string strs;
bool firstinit = true;
while ((strs = reader.ReadLine()) != null)
{
string name = strs.Split(_separatorForKeyValue)[0];
ShipsGenericCollection<DrawningShip, DrawningObjectShip> collection = new(_pictureWidth, _pictureHeight);
foreach (string data in strs.Split(_separatorForKeyValue)[1].Split(_separatorRecords))
{
DrawningShip? ship =
data?.CreateDrawningShip(_separatorForObject, _pictureWidth, _pictureHeight);
if (ship != null)
{
if (!(collection + ship))
{
return false;
}
}
}
_shipStorages.Add(name, collection);
}
return true;
}
}
}
}