2 Commits
lab04 ... 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
14 changed files with 942 additions and 8 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

@@ -39,17 +39,24 @@
listBoxStorages = new ListBox(); listBoxStorages = new ListBox();
buttonAddObject = new Button(); buttonAddObject = new Button();
textBoxStorageName = new TextBox(); 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(); 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;
@@ -154,6 +161,40 @@
textBoxStorageName.Size = new Size(136, 23); textBoxStorageName.Size = new Size(136, 23);
textBoxStorageName.TabIndex = 0; 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);
@@ -162,6 +203,8 @@
Controls.Add(groupBox2); 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();
@@ -169,6 +212,8 @@
groupBox1.PerformLayout(); groupBox1.PerformLayout();
groupBox2.ResumeLayout(false); groupBox2.ResumeLayout(false);
groupBox2.PerformLayout(); groupBox2.PerformLayout();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false); ResumeLayout(false);
PerformLayout(); PerformLayout();
} }
@@ -186,5 +231,11 @@
private ListBox listBoxStorages; private ListBox listBoxStorages;
private Button buttonAddObject; private Button buttonAddObject;
private TextBox textBoxStorageName; private TextBox textBoxStorageName;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem сохранениеToolStripMenuItem;
private ToolStripMenuItem загрузкаToolStripMenuItem;
private MenuStrip menuStrip;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
} }
} }

View File

@@ -113,10 +113,11 @@ namespace ProjectWarmlyShip
{ {
return; return;
} }
FormWarmlyShip form = new FormWarmlyShip(); FormShipConfig form = new FormShipConfig();
if (form.ShowDialog() == DialogResult.OK) Action<DrawningShip>? ShipDelegate = new((m) =>
{ {
if (obj + form.SelectedShip) bool q = (obj + m);
if (q)
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowShips(); pictureBoxCollection.Image = obj.ShowShips();
@@ -125,7 +126,9 @@ namespace ProjectWarmlyShip
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show("Не удалось добавить объект");
} }
} });
form.AddEvent(ShipDelegate);
form.Show();
} }
/// <summary> /// <summary>
/// Удаление объекта из набора /// Удаление объекта из набора
@@ -179,5 +182,47 @@ namespace ProjectWarmlyShip
} }
pictureBoxCollection.Image = obj.ShowShips(); 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

@@ -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;

View File

@@ -31,6 +31,18 @@ namespace ProjectWarmlyShip
/// </summary> /// </summary>
private readonly int _pictureHeight; private readonly int _pictureHeight;
/// <summary> /// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private static readonly char _separatorForKeyValue = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char _separatorRecords = ';';
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
/// <param name="pictureWidth"></param> /// <param name="pictureWidth"></param>
@@ -76,5 +88,86 @@ namespace ProjectWarmlyShip
return null; 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;
}
}
} }
} }