From 49eff77c1ac4b44340f621ee4ab8dd38e4b5b711 Mon Sep 17 00:00:00 2001 From: DelphyAlmond Date: Wed, 12 Jun 2024 14:29:35 +0400 Subject: [PATCH 01/13] encapsulation --- ProjectCruiser/DirectionType.cs | 15 ++ ProjectCruiser/DrawningBase.cs | 189 ++++++++++++++++++++++++++ ProjectCruiser/EntityBase.cs | 36 +++++ ProjectCruiser/OceanForm1.Designer.cs | 114 ++++++++++++++++ ProjectCruiser/OceanForm1.cs | 89 ++++++++++++ ProjectCruiser/OceanForm1.resx | 120 ++++++++++++++++ ProjectCruiser/Program.cs | 2 +- 7 files changed, 564 insertions(+), 1 deletion(-) create mode 100644 ProjectCruiser/DirectionType.cs create mode 100644 ProjectCruiser/DrawningBase.cs create mode 100644 ProjectCruiser/EntityBase.cs create mode 100644 ProjectCruiser/OceanForm1.Designer.cs create mode 100644 ProjectCruiser/OceanForm1.cs create mode 100644 ProjectCruiser/OceanForm1.resx diff --git a/ProjectCruiser/DirectionType.cs b/ProjectCruiser/DirectionType.cs new file mode 100644 index 0000000..d8cd3ba --- /dev/null +++ b/ProjectCruiser/DirectionType.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCruiser; + +public enum DirectionType +{ + Up = 1, + Down = 2, + Left = 3, + Right = 4 +} diff --git a/ProjectCruiser/DrawningBase.cs b/ProjectCruiser/DrawningBase.cs new file mode 100644 index 0000000..169cdc2 --- /dev/null +++ b/ProjectCruiser/DrawningBase.cs @@ -0,0 +1,189 @@ +using System.Drawing.Drawing2D; + +namespace ProjectCruiser; +public class DrawningBase +{ + // Класс-сущность + public EntityBase? EntityB { get; private set; } + private int? _pictureWidth; // Ширина окна + private int? _pictureHeight; // Высота окна + private int? _startPosX; // Левая координата прорисовки автомобиля + private int? _startPosY; // Верхняя кооридната прорисовки автомобиля + + private readonly int _drawningWidth = 300; // Ширина прорисовки автомобиля + private readonly int _drawningHeight = 42; // Высота прорисовки автомобиля + + // Инициализация свойств + public void Init(int speed, double weight, + Color bodyColor, Color additionalColor, bool pad, + bool hangar, bool deckhouse) + { + EntityB = new EntityBase(); + EntityB.Init(speed, weight, bodyColor, + additionalColor, pad, hangar, deckhouse); + + _pictureWidth = null; + _pictureHeight = null; + _startPosX = null; + _startPosY = null; + } + + public int getHeight() // для создания объекта в нижнем левом углу (*) + { + return _drawningHeight; + } + + // Установка границ поля + public bool SetPictureSize(int w, int h) + { + if (w > _pictureWidth || h > _pictureHeight) + { + return false; + } + + _pictureWidth = w; + _pictureHeight = h; + + if (_startPosX != null || _startPosY != null) + { + SetPosition(_startPosX.Value, _startPosY.Value); + } + + return true; + } + + public void SetPosition(int x, int y) + { + if (!_pictureHeight.HasValue || !_pictureWidth.HasValue) + { + return; + } + + if (x > _pictureWidth - _drawningWidth) _startPosX = + _pictureWidth - _drawningWidth; + else if (x < 0) _startPosX = 0; + else _startPosX = x; + + if (y > _pictureHeight - _drawningHeight) _startPosY = + _pictureHeight.Value - _drawningHeight; + else if (y < 0) _startPosY = 0; + else _startPosY = y; + } + + public bool MoveTransport(DirectionType direction) + { + if (EntityB == null || !_startPosX.HasValue || + !_startPosY.HasValue) + { + return false; + } + + switch (direction) + { + //влево + case DirectionType.Left: + if (_startPosX.Value - EntityB.Step > 0) + { + _startPosX -= (int)EntityB.Step; + } + return true; + //вверх + case DirectionType.Up: + if (_startPosY.Value - EntityB.Step > 0) + { + _startPosY -= (int)EntityB.Step; + } + return true; + // вправо + case DirectionType.Right: + if (_startPosX.Value + _drawningWidth + EntityB.Step + < _pictureWidth.Value) + { + _startPosX += (int)EntityB.Step; + } + return true; + //вниз + case DirectionType.Down: + if (_startPosY.Value + _drawningHeight + EntityB.Step + < _pictureHeight.Value) + { + _startPosY += (int)EntityB.Step; + } + return true; + + default: + return false; + // Перемещение объекта (удалось перемещение - true \ false) + } + } + + public void DrawTransport(Graphics g) + { + if (EntityB == null || !_startPosX.HasValue || + !_startPosY.HasValue) + { + return; + } + + Pen pen = new(Color.Black, 2); + Brush PadBrush = new HatchBrush(HatchStyle.DottedDiamond, Color.LightGray, Color.Black); + Brush additionalBrush = new SolidBrush(EntityB.AdditionalColor); + Brush mainBrush = new SolidBrush(EntityB.MainColor); + + //границы cruiser + Point point0 = new Point(_startPosX.Value + 2, _startPosY.Value + 7); + Point point1 = new Point(_startPosX.Value + 2, _startPosY.Value + 30); + Point point2 = new Point(_startPosX.Value + 184, _startPosY.Value + 42); + Point point3 = new Point(_startPosX.Value + 260, _startPosY.Value + 34); + Point point4 = new Point(_startPosX.Value + 300, _startPosY.Value + 22); + Point point5 = new Point(_startPosX.Value + 260, _startPosY.Value + 10); + Point point6 = new Point(_startPosX.Value + 184, _startPosY.Value + 2); + + Point[] boarders = { + point0, + point1, + point2, + point3, + point4, + point5, + point6 + }; + + g.DrawPolygon(pen, boarders); + g.FillPolygon(mainBrush, boarders); + + // вертолетная площадка + if (EntityB.HelicopterPads) + { + g.DrawEllipse(pen, _startPosX.Value + 170, _startPosY.Value + 11, 20, 20); + g.FillEllipse(PadBrush, _startPosX.Value + 170, _startPosY.Value + 11, 20, 20); + } + + // салон на верхней палубе + if (EntityB.Deckhouse) + { + // random location + int y_h = EntityB.values[1]; + g.DrawRectangle(pen, _startPosX.Value + 100, _startPosY.Value + y_h, 38, 24); // 40, 26 + + g.DrawRectangle(pen, _startPosX.Value + 110, _startPosY.Value + y_h + 6, 20, 12); + g.FillRectangle(additionalBrush, _startPosX.Value + 110, _startPosY.Value + y_h + 6, 20, 12); + g.DrawRectangle(pen, _startPosX.Value + 117, _startPosY.Value + y_h + 18, 6, 20); + g.FillRectangle(additionalBrush, _startPosX.Value + 117, _startPosY.Value + y_h + 18, 6, 20); + } + + // ангар + if (EntityB.Hangar) + { + int n = EntityB.values[2]; + if (n == 1) g.FillRectangle(additionalBrush, _startPosX.Value + 250, _startPosY.Value + 20, 14, 7); + + else + { + g.FillRectangle(additionalBrush, _startPosX.Value + 80, _startPosY.Value + 10, 10, 20); + g.FillRectangle(additionalBrush, _startPosX.Value + 70, _startPosY.Value + 12, 8, 12); + } + } + } +} + diff --git a/ProjectCruiser/EntityBase.cs b/ProjectCruiser/EntityBase.cs new file mode 100644 index 0000000..8d454ef --- /dev/null +++ b/ProjectCruiser/EntityBase.cs @@ -0,0 +1,36 @@ +namespace ProjectCruiser; + +public class EntityBase +{ + // свойства + public int Speed { get; private set; } // скорость + public double Weight { get; private set; } // вес + public Color MainColor { get; private set; } // основной цвет + public Color AdditionalColor { get; private set; } // доп. цвет + + // признаки (наличия) + public bool HelicopterPads { get; private set; } // вертолетная площадка + public bool Hangar { get; private set; } // ангар + public bool Deckhouse { get; private set; } // салон на верхней палубе + public double Step => Speed * 100 / Weight; + + public int[] values = { 0, 0, 0 }; + + public void Init(int speed, double weight, + Color mainc, Color addtc, bool pad, + bool hangar, bool deckhouse) + { + Random rn = new(); + + Speed = speed; + Weight = weight; + MainColor = mainc; + AdditionalColor = addtc; + HelicopterPads = pad; + Hangar = hangar; + Deckhouse = deckhouse; + values[0] = rn.Next(1, 4); + values[1] = rn.Next(5, 10); + values[2] = rn.Next(1, 3); + } +} diff --git a/ProjectCruiser/OceanForm1.Designer.cs b/ProjectCruiser/OceanForm1.Designer.cs new file mode 100644 index 0000000..eeab7be --- /dev/null +++ b/ProjectCruiser/OceanForm1.Designer.cs @@ -0,0 +1,114 @@ +namespace ProjectCruiser; +partial class OceanForm1 +{ + /// Required designer variable. + private System.ComponentModel.IContainer components = null; + + /// Clean up any resources being used. + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + private void InitializeComponent() + { + btnLeftArrow = new Button(); + btnDownArrow = new Button(); + btnRightArrow = new Button(); + btnUpArrow = new Button(); + btnCreateBase = new Button(); + pictureBoxCr = new PictureBox(); + ((System.ComponentModel.ISupportInitialize)pictureBoxCr).BeginInit(); + SuspendLayout(); + // + // btnLeftArrow + // + btnLeftArrow.Location = new Point(926, 634); + btnLeftArrow.Name = "btnLeftArrow"; + btnLeftArrow.Size = new Size(141, 132); + btnLeftArrow.TabIndex = 0; + btnLeftArrow.UseVisualStyleBackColor = true; + btnLeftArrow.Click += BtnMove_Click; + // + // btnDownArrow + // + btnDownArrow.Location = new Point(1073, 634); + btnDownArrow.Name = "btnDownArrow"; + btnDownArrow.Size = new Size(141, 132); + btnDownArrow.TabIndex = 1; + btnDownArrow.UseVisualStyleBackColor = true; + btnDownArrow.Click += BtnMove_Click; + // + // btnRightArrow + // + btnRightArrow.Location = new Point(1220, 634); + btnRightArrow.Name = "btnRightArrow"; + btnRightArrow.Size = new Size(141, 132); + btnRightArrow.TabIndex = 2; + btnRightArrow.UseVisualStyleBackColor = true; + btnRightArrow.Click += BtnMove_Click; + // + // btnUpArrow + // + btnUpArrow.Location = new Point(1073, 496); + btnUpArrow.Name = "btnUpArrow"; + btnUpArrow.Size = new Size(141, 132); + btnUpArrow.TabIndex = 3; + btnUpArrow.UseVisualStyleBackColor = true; + btnUpArrow.Click += BtnMove_Click; + // + // btnCreateBase + // + btnCreateBase.Location = new Point(928, 12); + btnCreateBase.Name = "btnCreateBase"; + btnCreateBase.Size = new Size(435, 46); + btnCreateBase.TabIndex = 4; + btnCreateBase.Text = "Create"; + btnCreateBase.UseVisualStyleBackColor = true; + btnCreateBase.Click += ButtonCreateBase_Click; + // + // pictureBoxCr + // + pictureBoxCr.Dock = DockStyle.Fill; + pictureBoxCr.Location = new Point(0, 0); + pictureBoxCr.Name = "pictureBoxCr"; + pictureBoxCr.Size = new Size(1375, 778); + pictureBoxCr.TabIndex = 5; + pictureBoxCr.TabStop = false; + // + // OceanForm1 + // + AutoScaleDimensions = new SizeF(13F, 32F); + AutoScaleMode = AutoScaleMode.Font; + BackColor = Color.Turquoise; + ClientSize = new Size(1375, 778); + Controls.Add(btnCreateBase); + Controls.Add(btnUpArrow); + Controls.Add(btnRightArrow); + Controls.Add(btnDownArrow); + Controls.Add(btnLeftArrow); + Controls.Add(pictureBoxCr); + Name = "OceanForm1"; + Text = "OceanForm1"; + ((System.ComponentModel.ISupportInitialize)pictureBoxCr).EndInit(); + ResumeLayout(false); + } + + #endregion + + private Button btnLeftArrow; + private Button btnDownArrow; + private Button btnRightArrow; + private Button btnUpArrow; + private Button btnCreateBase; + private PictureBox pictureBoxCr; +} \ No newline at end of file diff --git a/ProjectCruiser/OceanForm1.cs b/ProjectCruiser/OceanForm1.cs new file mode 100644 index 0000000..9c55215 --- /dev/null +++ b/ProjectCruiser/OceanForm1.cs @@ -0,0 +1,89 @@ +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 ProjectCruiser +{ + public partial class OceanForm1 : Form + { + // Поле-объект для прорисовки объекта + private DrawningBase? _drawningCruiser; + + public OceanForm1() + { + InitializeComponent(); + } + + // Метод прорисовки transport + private void Draw() + { + if (_drawningCruiser == null) + { + return; + } + Bitmap bmp = new(pictureBoxCr.Width, + pictureBoxCr.Height); + Graphics gr = Graphics.FromImage(bmp); + _drawningCruiser.DrawTransport(gr); + pictureBoxCr.Image = bmp; + } + + // Обработка нажатия кнопки "Create" + private void ButtonCreateBase_Click(object sender, EventArgs e) + { + Random random = new(); + _drawningCruiser = new DrawningBase(); + + _drawningCruiser.Init(random.Next(100, 300), random.Next(1000, 3000), + Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), + Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), + Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)), + Convert.ToBoolean(random.Next(0, 2))); + + _drawningCruiser.SetPictureSize(pictureBoxCr.Width, pictureBoxCr.Height); + _drawningCruiser.SetPosition(random.Next(10, 100), + pictureBoxCr.Height - random.Next(10, 100) - _drawningCruiser.getHeight()); + Draw(); + } + + + private void BtnMove_Click(object sender, EventArgs e) + { + if (_drawningCruiser == null) + { + return; + } + string name = ((Button)sender)?.Name ?? string.Empty; + bool result = false; + switch (name) + { + case "btnUpArrow": + result = + _drawningCruiser.MoveTransport(DirectionType.Up); + break; + case "btnDownArrow": + result = + _drawningCruiser.MoveTransport(DirectionType.Down); + break; + case "btnLeftArrow": + result = + _drawningCruiser.MoveTransport(DirectionType.Left); + break; + case "btnRightArrow": + result = + _drawningCruiser.MoveTransport(DirectionType.Right); + break; + } + if (result) + { + Draw(); + } + } + } +} diff --git a/ProjectCruiser/OceanForm1.resx b/ProjectCruiser/OceanForm1.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/ProjectCruiser/OceanForm1.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/ProjectCruiser/Program.cs b/ProjectCruiser/Program.cs index 2ddf3fc..5669fde 100644 --- a/ProjectCruiser/Program.cs +++ b/ProjectCruiser/Program.cs @@ -11,7 +11,7 @@ namespace ProjectCruiser // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new Form1()); + Application.Run(new OceanForm1()); } } } \ No newline at end of file -- 2.25.1 From 603cf3a903fcee722ad2186aa5487f3cd2758e31 Mon Sep 17 00:00:00 2001 From: DelphyAlmond Date: Wed, 12 Jun 2024 16:25:55 +0400 Subject: [PATCH 02/13] In process : Add Border & Center moving strategy --- ProjectCruiser/DirectionType.cs | 12 +--- ProjectCruiser/DrawningBase.cs | 100 ++++++++++++---------------- ProjectCruiser/DrawningCruiser.cs | 81 ++++++++++++++++++++++ ProjectCruiser/EntityBase.cs | 18 ++--- ProjectCruiser/EntityCruiser.cs | 19 ++++++ ProjectCruiser/IMoveableObj.cs | 16 +++++ ProjectCruiser/MoveableTransport.cs | 54 +++++++++++++++ ProjectCruiser/MovementDirection.cs | 16 +++++ ProjectCruiser/ObjParameters.cs | 29 ++++++++ ProjectCruiser/StrategyStatus.cs | 19 ++++++ 10 files changed, 283 insertions(+), 81 deletions(-) create mode 100644 ProjectCruiser/DrawningCruiser.cs create mode 100644 ProjectCruiser/EntityCruiser.cs create mode 100644 ProjectCruiser/IMoveableObj.cs create mode 100644 ProjectCruiser/MoveableTransport.cs create mode 100644 ProjectCruiser/MovementDirection.cs create mode 100644 ProjectCruiser/ObjParameters.cs create mode 100644 ProjectCruiser/StrategyStatus.cs diff --git a/ProjectCruiser/DirectionType.cs b/ProjectCruiser/DirectionType.cs index d8cd3ba..04733e1 100644 --- a/ProjectCruiser/DirectionType.cs +++ b/ProjectCruiser/DirectionType.cs @@ -1,15 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace ProjectCruiser; - +namespace ProjectCruiser; public enum DirectionType { + Unknown = -1, Up = 1, Down = 2, Left = 3, Right = 4 -} +} \ No newline at end of file diff --git a/ProjectCruiser/DrawningBase.cs b/ProjectCruiser/DrawningBase.cs index 169cdc2..34e98c0 100644 --- a/ProjectCruiser/DrawningBase.cs +++ b/ProjectCruiser/DrawningBase.cs @@ -1,33 +1,39 @@ -using System.Drawing.Drawing2D; - -namespace ProjectCruiser; +namespace ProjectCruiser; public class DrawningBase { // Класс-сущность - public EntityBase? EntityB { get; private set; } + public EntityBase? EntityTransport { get; protected set; } private int? _pictureWidth; // Ширина окна private int? _pictureHeight; // Высота окна - private int? _startPosX; // Левая координата прорисовки автомобиля - private int? _startPosY; // Верхняя кооридната прорисовки автомобиля + + protected int? _startPosX; // < protected + protected int? _startPosY; // < protected private readonly int _drawningWidth = 300; // Ширина прорисовки автомобиля private readonly int _drawningHeight = 42; // Высота прорисовки автомобиля - // Инициализация свойств - public void Init(int speed, double weight, - Color bodyColor, Color additionalColor, bool pad, - bool hangar, bool deckhouse) + // Инициализация свойств (теперь через конструктор) + public DrawningBase(int speed, double weight, + Color bodyColor) { - EntityB = new EntityBase(); - EntityB.Init(speed, weight, bodyColor, - additionalColor, pad, hangar, deckhouse); + EntityTransport = new EntityBase(speed, weight, bodyColor); + } + private DrawningBase() + { _pictureWidth = null; _pictureHeight = null; _startPosX = null; _startPosY = null; } + // protected > + protected DrawningBase(int drawningCarWidth, int drawningCarHeight) : this() + { + _drawningWidth = drawningCarWidth; + _pictureHeight = drawningCarHeight; + } + public int getHeight() // для создания объекта в нижнем левом углу (*) { return _drawningHeight; @@ -72,7 +78,7 @@ public class DrawningBase public bool MoveTransport(DirectionType direction) { - if (EntityB == null || !_startPosX.HasValue || + if (EntityTransport == null || !_startPosX.HasValue || !_startPosY.HasValue) { return false; @@ -82,32 +88,32 @@ public class DrawningBase { //влево case DirectionType.Left: - if (_startPosX.Value - EntityB.Step > 0) + if (_startPosX.Value - EntityTransport.Step > 0) { - _startPosX -= (int)EntityB.Step; + _startPosX -= (int)EntityTransport.Step; } return true; //вверх case DirectionType.Up: - if (_startPosY.Value - EntityB.Step > 0) + if (_startPosY.Value - EntityTransport.Step > 0) { - _startPosY -= (int)EntityB.Step; + _startPosY -= (int)EntityTransport.Step; } return true; // вправо case DirectionType.Right: - if (_startPosX.Value + _drawningWidth + EntityB.Step + if (_startPosX.Value + _drawningWidth + EntityTransport.Step < _pictureWidth.Value) { - _startPosX += (int)EntityB.Step; + _startPosX += (int)EntityTransport.Step; } return true; //вниз case DirectionType.Down: - if (_startPosY.Value + _drawningHeight + EntityB.Step + if (_startPosY.Value + _drawningHeight + EntityTransport.Step < _pictureHeight.Value) { - _startPosY += (int)EntityB.Step; + _startPosY += (int)EntityTransport.Step; } return true; @@ -117,18 +123,16 @@ public class DrawningBase } } - public void DrawTransport(Graphics g) + public virtual void DrawTransport(Graphics g) // < virtual { - if (EntityB == null || !_startPosX.HasValue || + if (EntityTransport == null || !_startPosX.HasValue || !_startPosY.HasValue) { return; } Pen pen = new(Color.Black, 2); - Brush PadBrush = new HatchBrush(HatchStyle.DottedDiamond, Color.LightGray, Color.Black); - Brush additionalBrush = new SolidBrush(EntityB.AdditionalColor); - Brush mainBrush = new SolidBrush(EntityB.MainColor); + Brush mainBrush = new SolidBrush(EntityTransport.MainColor); //границы cruiser Point point0 = new Point(_startPosX.Value + 2, _startPosY.Value + 7); @@ -152,38 +156,18 @@ public class DrawningBase g.DrawPolygon(pen, boarders); g.FillPolygon(mainBrush, boarders); - // вертолетная площадка - if (EntityB.HelicopterPads) - { - g.DrawEllipse(pen, _startPosX.Value + 170, _startPosY.Value + 11, 20, 20); - g.FillEllipse(PadBrush, _startPosX.Value + 170, _startPosY.Value + 11, 20, 20); - } - // салон на верхней палубе - if (EntityB.Deckhouse) - { - // random location - int y_h = EntityB.values[1]; - g.DrawRectangle(pen, _startPosX.Value + 100, _startPosY.Value + y_h, 38, 24); // 40, 26 - - g.DrawRectangle(pen, _startPosX.Value + 110, _startPosY.Value + y_h + 6, 20, 12); - g.FillRectangle(additionalBrush, _startPosX.Value + 110, _startPosY.Value + y_h + 6, 20, 12); - g.DrawRectangle(pen, _startPosX.Value + 117, _startPosY.Value + y_h + 18, 6, 20); - g.FillRectangle(additionalBrush, _startPosX.Value + 117, _startPosY.Value + y_h + 18, 6, 20); - } - - // ангар - if (EntityB.Hangar) - { - int n = EntityB.values[2]; - if (n == 1) g.FillRectangle(additionalBrush, _startPosX.Value + 250, _startPosY.Value + 20, 14, 7); - - else - { - g.FillRectangle(additionalBrush, _startPosX.Value + 80, _startPosY.Value + 10, 10, 20); - g.FillRectangle(additionalBrush, _startPosX.Value + 70, _startPosY.Value + 12, 8, 12); - } - } + int y_h = EntityTransport.values[1]; + g.DrawRectangle(pen, _startPosX.Value + 100, _startPosY.Value + y_h, 38, 24); + g.DrawRectangle(pen, _startPosX.Value + 110, _startPosY.Value + y_h + 6, 20, 12); + g.FillRectangle(mainBrush, _startPosX.Value + 110, _startPosY.Value + y_h + 6, 20, 12); + g.DrawRectangle(pen, _startPosX.Value + 117, _startPosY.Value + y_h + 18, 6, 20); + g.FillRectangle(mainBrush, _startPosX.Value + 117, _startPosY.Value + y_h + 18, 6, 20); } + + public int? GetPosX => _startPosX; + public int? GetPosY => _startPosY; + public int GetWidth => _drawningWidth; + public int GetHeight => _drawningHeight; } diff --git a/ProjectCruiser/DrawningCruiser.cs b/ProjectCruiser/DrawningCruiser.cs new file mode 100644 index 0000000..3225a76 --- /dev/null +++ b/ProjectCruiser/DrawningCruiser.cs @@ -0,0 +1,81 @@ +using System.Drawing.Drawing2D; + +namespace ProjectCruiser; +internal class DrawningCruiser : DrawningBase +{ + + private EntityCruiser EntityCruiser; + + public DrawningCruiser(int speed, double weight, Color bodyColor, + Color additionalColor, bool pads, bool hangar) : base(300, 42) + // all additional featchures 'inside' object, so size remains + { + EntityCruiser = new EntityCruiser(speed, weight, + bodyColor, additionalColor, pads, hangar); + } + + public override void DrawTransport(Graphics g) + { + if (EntityCruiser == null || !_startPosX.HasValue || !_startPosY.HasValue) + { + return; + } + + Pen pen = new(Color.Black, 2); + Brush PadBrush = new HatchBrush(HatchStyle.DottedDiamond, Color.LightGray, Color.Black); + Brush additionalBrush = new SolidBrush(EntityCruiser.AdditionalColor); + Brush mainBrush = new SolidBrush(EntityTransport.MainColor); + + //границы cruiser + Point point0 = new Point(_startPosX.Value + 2, _startPosY.Value + 7); + Point point1 = new Point(_startPosX.Value + 2, _startPosY.Value + 30); + Point point2 = new Point(_startPosX.Value + 184, _startPosY.Value + 42); + Point point3 = new Point(_startPosX.Value + 260, _startPosY.Value + 34); + Point point4 = new Point(_startPosX.Value + 300, _startPosY.Value + 22); + Point point5 = new Point(_startPosX.Value + 260, _startPosY.Value + 10); + Point point6 = new Point(_startPosX.Value + 184, _startPosY.Value + 2); + + Point[] boarders = { + point0, + point1, + point2, + point3, + point4, + point5, + point6 + }; + + g.DrawPolygon(pen, boarders); + g.FillPolygon(mainBrush, boarders); + + // салон на верхней палубе + // random location + int y_h = EntityCruiser.values[1]; + g.DrawRectangle(pen, _startPosX.Value + 100, _startPosY.Value + y_h, 38, 24); + + g.DrawRectangle(pen, _startPosX.Value + 110, _startPosY.Value + y_h + 6, 20, 12); + g.FillRectangle(additionalBrush, _startPosX.Value + 110, _startPosY.Value + y_h + 6, 20, 12); + g.DrawRectangle(pen, _startPosX.Value + 117, _startPosY.Value + y_h + 18, 6, 20); + g.FillRectangle(additionalBrush, _startPosX.Value + 117, _startPosY.Value + y_h + 18, 6, 20); + + // вертолетная площадка + if (EntityCruiser.HelicopterPads) + { + g.DrawEllipse(pen, _startPosX.Value + 170, _startPosY.Value + 11, 20, 20); + g.FillEllipse(PadBrush, _startPosX.Value + 170, _startPosY.Value + 11, 20, 20); + } + + // ангар + if (EntityCruiser.Hangar) + { + int n = EntityTransport.values[2]; + if (n == 1) g.FillRectangle(additionalBrush, _startPosX.Value + 250, _startPosY.Value + 20, 14, 7); + + else + { + g.FillRectangle(additionalBrush, _startPosX.Value + 80, _startPosY.Value + 10, 10, 20); + g.FillRectangle(additionalBrush, _startPosX.Value + 70, _startPosY.Value + 12, 8, 12); + } + } + } +} diff --git a/ProjectCruiser/EntityBase.cs b/ProjectCruiser/EntityBase.cs index 8d454ef..e2d865b 100644 --- a/ProjectCruiser/EntityBase.cs +++ b/ProjectCruiser/EntityBase.cs @@ -6,29 +6,19 @@ public class EntityBase public int Speed { get; private set; } // скорость public double Weight { get; private set; } // вес public Color MainColor { get; private set; } // основной цвет - public Color AdditionalColor { get; private set; } // доп. цвет - - // признаки (наличия) - public bool HelicopterPads { get; private set; } // вертолетная площадка - public bool Hangar { get; private set; } // ангар - public bool Deckhouse { get; private set; } // салон на верхней палубе + // public bool Deckhouse { get; private set; } // салон на верхней палубе public double Step => Speed * 100 / Weight; public int[] values = { 0, 0, 0 }; - public void Init(int speed, double weight, - Color mainc, Color addtc, bool pad, - bool hangar, bool deckhouse) + public EntityBase(int speed, double weight, + Color mainc) // (bool) deckhouse -> default TRUE now { Random rn = new(); - Speed = speed; Weight = weight; MainColor = mainc; - AdditionalColor = addtc; - HelicopterPads = pad; - Hangar = hangar; - Deckhouse = deckhouse; + // Deckhouse = deckhouse; values[0] = rn.Next(1, 4); values[1] = rn.Next(5, 10); values[2] = rn.Next(1, 3); diff --git a/ProjectCruiser/EntityCruiser.cs b/ProjectCruiser/EntityCruiser.cs new file mode 100644 index 0000000..7bfb66b --- /dev/null +++ b/ProjectCruiser/EntityCruiser.cs @@ -0,0 +1,19 @@ +namespace ProjectCruiser; + +public class EntityCruiser : EntityBase +{ + public Color AdditionalColor { get; private set; } // доп. цвет + + // признаки (наличия) + public bool HelicopterPads { get; private set; } // вертолетная площадка + public bool Hangar { get; private set; } // ангар + + public EntityCruiser(int speed, double weight, Color mainc, + Color additionalColor, bool pads, bool hangar) + : base(speed, weight, mainc) + { + AdditionalColor = additionalColor; + HelicopterPads = pads; + Hangar = hangar; + } +} diff --git a/ProjectCruiser/IMoveableObj.cs b/ProjectCruiser/IMoveableObj.cs new file mode 100644 index 0000000..ca821e7 --- /dev/null +++ b/ProjectCruiser/IMoveableObj.cs @@ -0,0 +1,16 @@ +namespace ProjectCruiser; + +// Интерфейс для работы с перемещаемым объектом +public interface IMoveableObj +{ + // Получение координат объекта + ObjParameters? GetObjectPosition { get; } + + // Получение шага объекта + int GetStep { get; } + + /// Попытка переместить объект в указанном направлении + /// Направление + /// true - объект перемещен, false - перемещение невозможно + bool TryMoveObject(MovementDirection direction); +} diff --git a/ProjectCruiser/MoveableTransport.cs b/ProjectCruiser/MoveableTransport.cs new file mode 100644 index 0000000..3717287 --- /dev/null +++ b/ProjectCruiser/MoveableTransport.cs @@ -0,0 +1,54 @@ +namespace ProjectCruiser; + +// Класс-реализация IMoveableObject с использованием DrawningBase +public class MoveableTransport : IMoveableObj +{ + // Поле-объект класса Drawning(Transport) или его наследника + private readonly DrawningBase? _car = null; + + public MoveableTransport(DrawningBase car) + { + _car = car; + } + + public ObjParameters? GetObjectPosition + { + get + { + if (_car == null || _car.EntityTransport == null || + !_car.GetPosX.HasValue || !_car.GetPosY.HasValue) + { + return null; + } + return new ObjParameters(_car.GetPosX.Value, + _car.GetPosY.Value, _car.GetWidth, _car.GetHeight); + } + } + + public int GetStep => (int)(_car?.EntityTransport?.Step ?? 0); + + public bool TryMoveObject(MovementDirection direction) + { + if (_car == null || _car.EntityTransport == null) + { + return false; + } + return _car.MoveTransport(GetDirectionType(direction)); + } + + /// Конвертация из MovementDirection в DirectionType + /// MovementDirection + /// DirectionType + private static DirectionType GetDirectionType(MovementDirection direction) + { + return direction switch + { + MovementDirection.Left => DirectionType.Left, + MovementDirection.Right => DirectionType.Right, + MovementDirection.Up => DirectionType.Up, + MovementDirection.Down => DirectionType.Down, + _ => DirectionType.Unknown, + }; + } +} + diff --git a/ProjectCruiser/MovementDirection.cs b/ProjectCruiser/MovementDirection.cs new file mode 100644 index 0000000..3a83b0d --- /dev/null +++ b/ProjectCruiser/MovementDirection.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCruiser; + +// Направление перемещения +public enum MovementDirection +{ + Up = 1, + Down = 2, + Left = 3, + Right = 4 +} diff --git a/ProjectCruiser/ObjParameters.cs b/ProjectCruiser/ObjParameters.cs new file mode 100644 index 0000000..b2eb447 --- /dev/null +++ b/ProjectCruiser/ObjParameters.cs @@ -0,0 +1,29 @@ +namespace ProjectCruiser; + +// Параметры-координаты объекта +public class ObjParameters +{ + private readonly int _x; + private readonly int _y; + + private readonly int _width; // Ширина объекта + private readonly int _height; // Высота объекта + + public int LeftBorder => _x; // Левая граница + public int TopBorder => _y; // Верхняя граница + public int RightBorder => _x + _width; // Правая граница + public int DownBorder => _y + _height; // Нижняя граница + + // Вертикальная середина объекта + public int ObjectMiddleHorizontal => _x + _width / 2; + // Горизонтальная середина объекта + public int ObjectMiddleVertical => _y + _height / 2; + + public ObjParameters(int x, int y, int width, int height) + { + _x = x; + _y = y; + _width = width; + _height = height; + } +} diff --git a/ProjectCruiser/StrategyStatus.cs b/ProjectCruiser/StrategyStatus.cs new file mode 100644 index 0000000..233da87 --- /dev/null +++ b/ProjectCruiser/StrategyStatus.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCruiser; + +// Статус выполнения операции перемещения +public enum StrategyStatus +{ + // готово к началу + NotInit, + // Выполняется + InProgress, + // Завершено + Finish +} + -- 2.25.1 From cb015204b91a7e62bfd1dad10bb39c44caeb452a Mon Sep 17 00:00:00 2001 From: DelphyAlmond Date: Wed, 12 Jun 2024 19:21:59 +0400 Subject: [PATCH 03/13] inheritance --- ProjectCruiser/DrawningCruiser.cs | 81 ---------------- .../{ => DrawningSamples}/DirectionType.cs | 2 +- .../{ => DrawningSamples}/DrawningBase.cs | 14 +-- .../DrawningSamples/DrawningCruiser.cs | 54 +++++++++++ ProjectCruiser/{ => Entities}/EntityBase.cs | 7 +- .../{ => Entities}/EntityCruiser.cs | 2 +- .../MoveStrategy/AbstractStrategy.cs | 88 ++++++++++++++++++ .../{ => MoveStrategy}/IMoveableObj.cs | 2 +- ProjectCruiser/MoveStrategy/MoveToBorder.cs | 53 +++++++++++ ProjectCruiser/MoveStrategy/MoveToCentre.cs | 50 ++++++++++ .../{ => MoveStrategy}/MoveableTransport.cs | 4 +- .../MoveStrategy/MovementDirection.cs | 10 ++ .../{ => MoveStrategy}/ObjParameters.cs | 2 +- .../{ => MoveStrategy}/StrategyStatus.cs | 8 +- ProjectCruiser/MovementDirection.cs | 16 ---- ProjectCruiser/OceanForm1.Designer.cs | 52 +++++++++-- ProjectCruiser/OceanForm1.cs | 93 +++++++++++++++---- 17 files changed, 392 insertions(+), 146 deletions(-) delete mode 100644 ProjectCruiser/DrawningCruiser.cs rename ProjectCruiser/{ => DrawningSamples}/DirectionType.cs (68%) rename ProjectCruiser/{ => DrawningSamples}/DrawningBase.cs (92%) create mode 100644 ProjectCruiser/DrawningSamples/DrawningCruiser.cs rename ProjectCruiser/{ => Entities}/EntityBase.cs (82%) rename ProjectCruiser/{ => Entities}/EntityCruiser.cs (93%) create mode 100644 ProjectCruiser/MoveStrategy/AbstractStrategy.cs rename ProjectCruiser/{ => MoveStrategy}/IMoveableObj.cs (93%) create mode 100644 ProjectCruiser/MoveStrategy/MoveToBorder.cs create mode 100644 ProjectCruiser/MoveStrategy/MoveToCentre.cs rename ProjectCruiser/{ => MoveStrategy}/MoveableTransport.cs (95%) create mode 100644 ProjectCruiser/MoveStrategy/MovementDirection.cs rename ProjectCruiser/{ => MoveStrategy}/ObjParameters.cs (95%) rename ProjectCruiser/{ => MoveStrategy}/StrategyStatus.cs (62%) delete mode 100644 ProjectCruiser/MovementDirection.cs diff --git a/ProjectCruiser/DrawningCruiser.cs b/ProjectCruiser/DrawningCruiser.cs deleted file mode 100644 index 3225a76..0000000 --- a/ProjectCruiser/DrawningCruiser.cs +++ /dev/null @@ -1,81 +0,0 @@ -using System.Drawing.Drawing2D; - -namespace ProjectCruiser; -internal class DrawningCruiser : DrawningBase -{ - - private EntityCruiser EntityCruiser; - - public DrawningCruiser(int speed, double weight, Color bodyColor, - Color additionalColor, bool pads, bool hangar) : base(300, 42) - // all additional featchures 'inside' object, so size remains - { - EntityCruiser = new EntityCruiser(speed, weight, - bodyColor, additionalColor, pads, hangar); - } - - public override void DrawTransport(Graphics g) - { - if (EntityCruiser == null || !_startPosX.HasValue || !_startPosY.HasValue) - { - return; - } - - Pen pen = new(Color.Black, 2); - Brush PadBrush = new HatchBrush(HatchStyle.DottedDiamond, Color.LightGray, Color.Black); - Brush additionalBrush = new SolidBrush(EntityCruiser.AdditionalColor); - Brush mainBrush = new SolidBrush(EntityTransport.MainColor); - - //границы cruiser - Point point0 = new Point(_startPosX.Value + 2, _startPosY.Value + 7); - Point point1 = new Point(_startPosX.Value + 2, _startPosY.Value + 30); - Point point2 = new Point(_startPosX.Value + 184, _startPosY.Value + 42); - Point point3 = new Point(_startPosX.Value + 260, _startPosY.Value + 34); - Point point4 = new Point(_startPosX.Value + 300, _startPosY.Value + 22); - Point point5 = new Point(_startPosX.Value + 260, _startPosY.Value + 10); - Point point6 = new Point(_startPosX.Value + 184, _startPosY.Value + 2); - - Point[] boarders = { - point0, - point1, - point2, - point3, - point4, - point5, - point6 - }; - - g.DrawPolygon(pen, boarders); - g.FillPolygon(mainBrush, boarders); - - // салон на верхней палубе - // random location - int y_h = EntityCruiser.values[1]; - g.DrawRectangle(pen, _startPosX.Value + 100, _startPosY.Value + y_h, 38, 24); - - g.DrawRectangle(pen, _startPosX.Value + 110, _startPosY.Value + y_h + 6, 20, 12); - g.FillRectangle(additionalBrush, _startPosX.Value + 110, _startPosY.Value + y_h + 6, 20, 12); - g.DrawRectangle(pen, _startPosX.Value + 117, _startPosY.Value + y_h + 18, 6, 20); - g.FillRectangle(additionalBrush, _startPosX.Value + 117, _startPosY.Value + y_h + 18, 6, 20); - - // вертолетная площадка - if (EntityCruiser.HelicopterPads) - { - g.DrawEllipse(pen, _startPosX.Value + 170, _startPosY.Value + 11, 20, 20); - g.FillEllipse(PadBrush, _startPosX.Value + 170, _startPosY.Value + 11, 20, 20); - } - - // ангар - if (EntityCruiser.Hangar) - { - int n = EntityTransport.values[2]; - if (n == 1) g.FillRectangle(additionalBrush, _startPosX.Value + 250, _startPosY.Value + 20, 14, 7); - - else - { - g.FillRectangle(additionalBrush, _startPosX.Value + 80, _startPosY.Value + 10, 10, 20); - g.FillRectangle(additionalBrush, _startPosX.Value + 70, _startPosY.Value + 12, 8, 12); - } - } - } -} diff --git a/ProjectCruiser/DirectionType.cs b/ProjectCruiser/DrawningSamples/DirectionType.cs similarity index 68% rename from ProjectCruiser/DirectionType.cs rename to ProjectCruiser/DrawningSamples/DirectionType.cs index 04733e1..508a382 100644 --- a/ProjectCruiser/DirectionType.cs +++ b/ProjectCruiser/DrawningSamples/DirectionType.cs @@ -1,4 +1,4 @@ -namespace ProjectCruiser; +namespace ProjectCruiser.DrawningSamples; public enum DirectionType { Unknown = -1, diff --git a/ProjectCruiser/DrawningBase.cs b/ProjectCruiser/DrawningSamples/DrawningBase.cs similarity index 92% rename from ProjectCruiser/DrawningBase.cs rename to ProjectCruiser/DrawningSamples/DrawningBase.cs index 34e98c0..4b7884f 100644 --- a/ProjectCruiser/DrawningBase.cs +++ b/ProjectCruiser/DrawningSamples/DrawningBase.cs @@ -1,4 +1,5 @@ -namespace ProjectCruiser; +using ProjectCruiser.Entities; +namespace ProjectCruiser.DrawningSamples; public class DrawningBase { // Класс-сущность @@ -9,12 +10,11 @@ public class DrawningBase protected int? _startPosX; // < protected protected int? _startPosY; // < protected - private readonly int _drawningWidth = 300; // Ширина прорисовки автомобиля + private readonly int _drawningWidth = 302; // Ширина прорисовки автомобиля private readonly int _drawningHeight = 42; // Высота прорисовки автомобиля // Инициализация свойств (теперь через конструктор) - public DrawningBase(int speed, double weight, - Color bodyColor) + public DrawningBase(int speed, double weight, Color bodyColor) : this() { EntityTransport = new EntityBase(speed, weight, bodyColor); } @@ -42,7 +42,8 @@ public class DrawningBase // Установка границ поля public bool SetPictureSize(int w, int h) { - if (w > _pictureWidth || h > _pictureHeight) + if (w < _drawningWidth || h < _drawningHeight) + // canvas always bigger then obj to fit it { return false; } @@ -78,8 +79,7 @@ public class DrawningBase public bool MoveTransport(DirectionType direction) { - if (EntityTransport == null || !_startPosX.HasValue || - !_startPosY.HasValue) + if (EntityTransport == null || !_startPosX.HasValue || !_startPosY.HasValue) { return false; } diff --git a/ProjectCruiser/DrawningSamples/DrawningCruiser.cs b/ProjectCruiser/DrawningSamples/DrawningCruiser.cs new file mode 100644 index 0000000..90127e5 --- /dev/null +++ b/ProjectCruiser/DrawningSamples/DrawningCruiser.cs @@ -0,0 +1,54 @@ +using System.Drawing.Drawing2D; +using ProjectCruiser.Entities; +namespace ProjectCruiser.DrawningSamples; + +public class DrawningCruiser : DrawningBase +{ + // Инициализация свойств (все параметры класса (сущности)) + public DrawningCruiser(int speed, double weight, Color bodyColor, + Color additionalColor, bool pads, bool hangar) : base(302, 42) + // all additional featchures 'inside' object, so size remains + { + EntityTransport = new EntityCruiser(speed, weight, + bodyColor, additionalColor, pads, hangar); + } + + public override void DrawTransport(Graphics g) + { + if (EntityTransport == null || EntityTransport is not EntityCruiser ship || + !_startPosX.HasValue || !_startPosY.HasValue) // [ !!! ] :O + { + return; + } + + Pen pen = new(Color.Black, 2); + Brush PadBrush = new HatchBrush(HatchStyle.DottedDiamond, Color.LightGray, Color.Black); + Brush additionalBrush = new SolidBrush(ship.AdditionalColor); + + //границы cruiser <...> + // & + // салон на верхней палубе : + + base.DrawTransport(g); + + // вертолетная площадка + if (ship.HelicopterPads) + { + g.DrawEllipse(pen, _startPosX.Value + 170, _startPosY.Value + 11, 20, 20); + g.FillEllipse(PadBrush, _startPosX.Value + 170, _startPosY.Value + 11, 20, 20); + } + + // ангар + if (ship.Hangar) + { + int n = EntityTransport.values[2]; + if (n == 1) g.FillRectangle(additionalBrush, _startPosX.Value + 250, _startPosY.Value + 20, 14, 7); + + else + { + g.FillRectangle(additionalBrush, _startPosX.Value + 80, _startPosY.Value + 10, 10, 20); + g.FillRectangle(additionalBrush, _startPosX.Value + 70, _startPosY.Value + 12, 8, 12); + } + } + } +} diff --git a/ProjectCruiser/EntityBase.cs b/ProjectCruiser/Entities/EntityBase.cs similarity index 82% rename from ProjectCruiser/EntityBase.cs rename to ProjectCruiser/Entities/EntityBase.cs index e2d865b..f9aac46 100644 --- a/ProjectCruiser/EntityBase.cs +++ b/ProjectCruiser/Entities/EntityBase.cs @@ -1,4 +1,4 @@ -namespace ProjectCruiser; +namespace ProjectCruiser.Entities; public class EntityBase { @@ -6,13 +6,14 @@ public class EntityBase public int Speed { get; private set; } // скорость public double Weight { get; private set; } // вес public Color MainColor { get; private set; } // основной цвет + // public bool Deckhouse { get; private set; } // салон на верхней палубе public double Step => Speed * 100 / Weight; public int[] values = { 0, 0, 0 }; - public EntityBase(int speed, double weight, - Color mainc) // (bool) deckhouse -> default TRUE now + public EntityBase(int speed, double weight, Color mainc) + // (bool) deckhouse -> default TRUE now { Random rn = new(); Speed = speed; diff --git a/ProjectCruiser/EntityCruiser.cs b/ProjectCruiser/Entities/EntityCruiser.cs similarity index 93% rename from ProjectCruiser/EntityCruiser.cs rename to ProjectCruiser/Entities/EntityCruiser.cs index 7bfb66b..e251e02 100644 --- a/ProjectCruiser/EntityCruiser.cs +++ b/ProjectCruiser/Entities/EntityCruiser.cs @@ -1,4 +1,4 @@ -namespace ProjectCruiser; +namespace ProjectCruiser.Entities; public class EntityCruiser : EntityBase { diff --git a/ProjectCruiser/MoveStrategy/AbstractStrategy.cs b/ProjectCruiser/MoveStrategy/AbstractStrategy.cs new file mode 100644 index 0000000..e2004ba --- /dev/null +++ b/ProjectCruiser/MoveStrategy/AbstractStrategy.cs @@ -0,0 +1,88 @@ +namespace ProjectCruiser.MoveStrategy; + +public abstract class AbstractStrategy +{ + // Перемещаемый объект + private IMoveableObj? _moveableObject; + + // Статус перемещения (default установка) + private StrategyStatus _state = StrategyStatus.NotInit; + + // Ширина поля + protected int FieldWidth { get; private set; } + + // Высота поля + protected int FieldHeight { get; private set; } + + // Получение статуса + public StrategyStatus GetStatus() { return _state; } + + // Установка данных + public void SetData(IMoveableObj moveableObject, int width, int height) + { + if (moveableObject == null) + { + _state = StrategyStatus.NotInit; + return; + } + _state = StrategyStatus.InProgress; + _moveableObject = moveableObject; + FieldWidth = width; + FieldHeight = height; + } + + // Шаг перемещения + public void MakeStep() + { + if (_state != StrategyStatus.InProgress) + { + return; + } + if (IsTargetDestination()) + { + _state = StrategyStatus.Finish; + return; + } + MoveToTarget(); + } + + // Результаты перемещения + protected bool MoveLeft() => MoveTo(MovementDirection.Left); + protected bool MoveRight() => MoveTo(MovementDirection.Right); + protected bool MoveUp() => MoveTo(MovementDirection.Up); + protected bool MoveDown() => MoveTo(MovementDirection.Down); + + + // Параметры объекта + protected ObjParameters? GetObjectParameters => + _moveableObject?.GetObjectPosition; + + // Шаг объекта + protected int? GetStep() + { + if (_state != StrategyStatus.InProgress) + { + return null; + } + return _moveableObject?.GetStep; + } + + // Перемещение к цели + protected abstract void MoveToTarget(); + + // Проверка, достигнута ли цель + protected abstract bool IsTargetDestination(); + + + /// Попытка перемещения в требуемом направлении + /// Направление + /// Результат попытки (true - удалось переместиться, false - неудача) + private bool MoveTo(MovementDirection movementDirection) + { + if (_state != StrategyStatus.InProgress) + { + return false; + } + return _moveableObject?.TryMoveObject(movementDirection) ?? false; + } +} diff --git a/ProjectCruiser/IMoveableObj.cs b/ProjectCruiser/MoveStrategy/IMoveableObj.cs similarity index 93% rename from ProjectCruiser/IMoveableObj.cs rename to ProjectCruiser/MoveStrategy/IMoveableObj.cs index ca821e7..3af89c4 100644 --- a/ProjectCruiser/IMoveableObj.cs +++ b/ProjectCruiser/MoveStrategy/IMoveableObj.cs @@ -1,4 +1,4 @@ -namespace ProjectCruiser; +namespace ProjectCruiser.MoveStrategy; // Интерфейс для работы с перемещаемым объектом public interface IMoveableObj diff --git a/ProjectCruiser/MoveStrategy/MoveToBorder.cs b/ProjectCruiser/MoveStrategy/MoveToBorder.cs new file mode 100644 index 0000000..22137e2 --- /dev/null +++ b/ProjectCruiser/MoveStrategy/MoveToBorder.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCruiser.MoveStrategy; + +public class MoveToBorder : AbstractStrategy +{ + protected override bool IsTargetDestination() + { + ObjParameters? objP = GetObjectParameters; + if (objP == null) + { + return false; + } + + return FieldWidth - GetStep() < objP.RightBorder + && FieldHeight - GetStep() < objP.DownBorder; + } + + protected override void MoveToTarget() + { + ObjParameters? objP = GetObjectParameters; + if (objP == null) + { + return; + } + + int s = (int)GetStep(); + + int diffx = objP.RightBorder - FieldWidth; + if (Math.Abs(diffx) > GetStep()) + { + if (diffx > 0) + { + MoveLeft(); + } + else { MoveRight(); } + } + + int diffy = objP.DownBorder - FieldHeight; // (... - s) - step unnecessary + if (Math.Abs(diffy) > GetStep()) + { + if (diffy > 0) + { + MoveUp(); + } + else { MoveDown(); } + } + } +} diff --git a/ProjectCruiser/MoveStrategy/MoveToCentre.cs b/ProjectCruiser/MoveStrategy/MoveToCentre.cs new file mode 100644 index 0000000..493cee5 --- /dev/null +++ b/ProjectCruiser/MoveStrategy/MoveToCentre.cs @@ -0,0 +1,50 @@ +namespace ProjectCruiser.MoveStrategy; + +public class MoveToCentre : AbstractStrategy +{ + protected override bool IsTargetDestination() + { + ObjParameters? objP = GetObjectParameters; + if (objP == null) + { + return false; + } + + return objP.ObjectMiddleHorizontal - GetStep() + <= FieldWidth / 2 && objP.ObjectMiddleHorizontal + + GetStep() >= FieldWidth / 2 + + && objP.ObjectMiddleVertical - GetStep() + <= FieldHeight / 2 && objP.ObjectMiddleVertical + + GetStep() >= FieldHeight / 2; + } + + protected override void MoveToTarget() + { + ObjParameters? objP = GetObjectParameters; + if (objP == null) + { + return; + } + + int diffx = objP.ObjectMiddleHorizontal - FieldWidth / 2; + if (Math.Abs(diffx) > GetStep()) + { + if (diffx > 0) + { + MoveLeft(); + } + else { MoveRight(); } + } + + int diffy = objP.ObjectMiddleVertical - FieldHeight / 2; + if (Math.Abs(diffy) > GetStep()) + { + if (diffy > 0) + { + MoveUp(); + } + else { MoveDown(); } + } + } +} diff --git a/ProjectCruiser/MoveableTransport.cs b/ProjectCruiser/MoveStrategy/MoveableTransport.cs similarity index 95% rename from ProjectCruiser/MoveableTransport.cs rename to ProjectCruiser/MoveStrategy/MoveableTransport.cs index 3717287..aab74a4 100644 --- a/ProjectCruiser/MoveableTransport.cs +++ b/ProjectCruiser/MoveStrategy/MoveableTransport.cs @@ -1,4 +1,6 @@ -namespace ProjectCruiser; +using ProjectCruiser.DrawningSamples; + +namespace ProjectCruiser.MoveStrategy; // Класс-реализация IMoveableObject с использованием DrawningBase public class MoveableTransport : IMoveableObj diff --git a/ProjectCruiser/MoveStrategy/MovementDirection.cs b/ProjectCruiser/MoveStrategy/MovementDirection.cs new file mode 100644 index 0000000..9404d45 --- /dev/null +++ b/ProjectCruiser/MoveStrategy/MovementDirection.cs @@ -0,0 +1,10 @@ +namespace ProjectCruiser.MoveStrategy; + +// Направление перемещения +public enum MovementDirection +{ + Up = 1, + Down = 2, + Left = 3, + Right = 4 +} diff --git a/ProjectCruiser/ObjParameters.cs b/ProjectCruiser/MoveStrategy/ObjParameters.cs similarity index 95% rename from ProjectCruiser/ObjParameters.cs rename to ProjectCruiser/MoveStrategy/ObjParameters.cs index b2eb447..428f1eb 100644 --- a/ProjectCruiser/ObjParameters.cs +++ b/ProjectCruiser/MoveStrategy/ObjParameters.cs @@ -1,4 +1,4 @@ -namespace ProjectCruiser; +namespace ProjectCruiser.MoveStrategy; // Параметры-координаты объекта public class ObjParameters diff --git a/ProjectCruiser/StrategyStatus.cs b/ProjectCruiser/MoveStrategy/StrategyStatus.cs similarity index 62% rename from ProjectCruiser/StrategyStatus.cs rename to ProjectCruiser/MoveStrategy/StrategyStatus.cs index 233da87..d2d7608 100644 --- a/ProjectCruiser/StrategyStatus.cs +++ b/ProjectCruiser/MoveStrategy/StrategyStatus.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace ProjectCruiser; +namespace ProjectCruiser.MoveStrategy; // Статус выполнения операции перемещения public enum StrategyStatus diff --git a/ProjectCruiser/MovementDirection.cs b/ProjectCruiser/MovementDirection.cs deleted file mode 100644 index 3a83b0d..0000000 --- a/ProjectCruiser/MovementDirection.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace ProjectCruiser; - -// Направление перемещения -public enum MovementDirection -{ - Up = 1, - Down = 2, - Left = 3, - Right = 4 -} diff --git a/ProjectCruiser/OceanForm1.Designer.cs b/ProjectCruiser/OceanForm1.Designer.cs index eeab7be..611ed06 100644 --- a/ProjectCruiser/OceanForm1.Designer.cs +++ b/ProjectCruiser/OceanForm1.Designer.cs @@ -27,12 +27,15 @@ partial class OceanForm1 btnUpArrow = new Button(); btnCreateBase = new Button(); pictureBoxCr = new PictureBox(); + comboBoxStrategy = new ComboBox(); + btnCreateAdvanced = new Button(); + btnActivateStrategy = new Button(); ((System.ComponentModel.ISupportInitialize)pictureBoxCr).BeginInit(); SuspendLayout(); // // btnLeftArrow // - btnLeftArrow.Location = new Point(926, 634); + btnLeftArrow.Location = new Point(926, 445); btnLeftArrow.Name = "btnLeftArrow"; btnLeftArrow.Size = new Size(141, 132); btnLeftArrow.TabIndex = 0; @@ -41,7 +44,7 @@ partial class OceanForm1 // // btnDownArrow // - btnDownArrow.Location = new Point(1073, 634); + btnDownArrow.Location = new Point(1073, 445); btnDownArrow.Name = "btnDownArrow"; btnDownArrow.Size = new Size(141, 132); btnDownArrow.TabIndex = 1; @@ -50,7 +53,7 @@ partial class OceanForm1 // // btnRightArrow // - btnRightArrow.Location = new Point(1220, 634); + btnRightArrow.Location = new Point(1220, 445); btnRightArrow.Name = "btnRightArrow"; btnRightArrow.Size = new Size(141, 132); btnRightArrow.TabIndex = 2; @@ -59,7 +62,7 @@ partial class OceanForm1 // // btnUpArrow // - btnUpArrow.Location = new Point(1073, 496); + btnUpArrow.Location = new Point(1073, 307); btnUpArrow.Name = "btnUpArrow"; btnUpArrow.Size = new Size(141, 132); btnUpArrow.TabIndex = 3; @@ -70,11 +73,11 @@ partial class OceanForm1 // btnCreateBase.Location = new Point(928, 12); btnCreateBase.Name = "btnCreateBase"; - btnCreateBase.Size = new Size(435, 46); + btnCreateBase.Size = new Size(433, 46); btnCreateBase.TabIndex = 4; - btnCreateBase.Text = "Create"; + btnCreateBase.Text = "Create base object"; btnCreateBase.UseVisualStyleBackColor = true; - btnCreateBase.Click += ButtonCreateBase_Click; + btnCreateBase.Click += btnCreateBase_Click; // // pictureBoxCr // @@ -85,12 +88,44 @@ partial class OceanForm1 pictureBoxCr.TabIndex = 5; pictureBoxCr.TabStop = false; // + // comboBoxStrategy + // + comboBoxStrategy.FormattingEnabled = true; + comboBoxStrategy.Items.AddRange(new object[] { "centre", "border" }); + comboBoxStrategy.Location = new Point(928, 120); + comboBoxStrategy.Name = "comboBoxStrategy"; + comboBoxStrategy.Size = new Size(435, 40); + comboBoxStrategy.TabIndex = 6; + // + // btnCreateAdvanced + // + btnCreateAdvanced.Location = new Point(928, 58); + btnCreateAdvanced.Name = "btnCreateAdvanced"; + btnCreateAdvanced.Size = new Size(433, 46); + btnCreateAdvanced.TabIndex = 7; + btnCreateAdvanced.Text = "Create advanced object"; + btnCreateAdvanced.UseVisualStyleBackColor = true; + btnCreateAdvanced.Click += btnCreateAdvanced_Click; + // + // btnActivateStrategy + // + btnActivateStrategy.Location = new Point(928, 166); + btnActivateStrategy.Name = "btnActivateStrategy"; + btnActivateStrategy.Size = new Size(435, 46); + btnActivateStrategy.TabIndex = 8; + btnActivateStrategy.Text = "Activate path"; + btnActivateStrategy.UseVisualStyleBackColor = true; + btnActivateStrategy.Click += ButtonStrategyStep_Click; + // // OceanForm1 // AutoScaleDimensions = new SizeF(13F, 32F); AutoScaleMode = AutoScaleMode.Font; BackColor = Color.Turquoise; ClientSize = new Size(1375, 778); + Controls.Add(btnActivateStrategy); + Controls.Add(btnCreateAdvanced); + Controls.Add(comboBoxStrategy); Controls.Add(btnCreateBase); Controls.Add(btnUpArrow); Controls.Add(btnRightArrow); @@ -111,4 +146,7 @@ partial class OceanForm1 private Button btnUpArrow; private Button btnCreateBase; private PictureBox pictureBoxCr; + private ComboBox comboBoxStrategy; + private Button btnCreateAdvanced; + private Button btnActivateStrategy; } \ No newline at end of file diff --git a/ProjectCruiser/OceanForm1.cs b/ProjectCruiser/OceanForm1.cs index 9c55215..f214473 100644 --- a/ProjectCruiser/OceanForm1.cs +++ b/ProjectCruiser/OceanForm1.cs @@ -1,12 +1,5 @@ -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; +using ProjectCruiser.DrawningSamples; +using ProjectCruiser.MoveStrategy; namespace ProjectCruiser { @@ -15,9 +8,13 @@ namespace ProjectCruiser // Поле-объект для прорисовки объекта private DrawningBase? _drawningCruiser; + // Стратегия перемещения + private AbstractStrategy? _strategy; + public OceanForm1() { InitializeComponent(); + _strategy = null; } // Метод прорисовки transport @@ -27,32 +24,52 @@ namespace ProjectCruiser { return; } - Bitmap bmp = new(pictureBoxCr.Width, - pictureBoxCr.Height); + Bitmap bmp = new(pictureBoxCr.Width, pictureBoxCr.Height); Graphics gr = Graphics.FromImage(bmp); _drawningCruiser.DrawTransport(gr); pictureBoxCr.Image = bmp; } - // Обработка нажатия кнопки "Create" - private void ButtonCreateBase_Click(object sender, EventArgs e) + // Обработка нажатия кнопок "Create(...)" + + private void btnCreateBase_Click(object sender, EventArgs e) => + CreateObject(nameof(DrawningBase)); + + private void btnCreateAdvanced_Click(object sender, EventArgs e) => + CreateObject(nameof(DrawningCruiser)); + + // Создание объекта класса-перемещения + /// Тип создаваемого объекта + private void CreateObject(string type) { Random random = new(); - _drawningCruiser = new DrawningBase(); + switch (type) + { + case nameof(DrawningBase): + _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))); + break; - _drawningCruiser.Init(random.Next(100, 300), random.Next(1000, 3000), - Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), - Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), - Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)), - Convert.ToBoolean(random.Next(0, 2))); + case nameof(DrawningCruiser): + _drawningCruiser = new DrawningCruiser(random.Next(100, 300), random.Next(1000, 3000), + Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), + Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), + Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2))); + break; + + default: + return; + } _drawningCruiser.SetPictureSize(pictureBoxCr.Width, pictureBoxCr.Height); _drawningCruiser.SetPosition(random.Next(10, 100), pictureBoxCr.Height - random.Next(10, 100) - _drawningCruiser.getHeight()); + + _strategy = null; + comboBoxStrategy.Enabled = true; Draw(); } - private void BtnMove_Click(object sender, EventArgs e) { if (_drawningCruiser == null) @@ -85,5 +102,41 @@ namespace ProjectCruiser Draw(); } } + + private void ButtonStrategyStep_Click(object sender, EventArgs e) + { + if (_drawningCruiser == null) + { + return; + } + if (comboBoxStrategy.Enabled) + { + _strategy = comboBoxStrategy.SelectedIndex switch + { + 0 => new MoveToCentre(), + 1 => new MoveToBorder(), + _ => null, + }; + if (_strategy == null) + { + return; + } + _strategy.SetData(new MoveableTransport(_drawningCruiser), + pictureBoxCr.Width, pictureBoxCr.Height); + } + if (_strategy == null) + { + return; + } + comboBoxStrategy.Enabled = false; + _strategy.MakeStep(); + Draw(); + + if (_strategy.GetStatus() == StrategyStatus.Finish) + { + comboBoxStrategy.Enabled = true; + _strategy = null; + } + } } } -- 2.25.1 From 8733297af1aec1a88f89e4ab5f14b60393f6c85d Mon Sep 17 00:00:00 2001 From: DelphyAlmond Date: Thu, 13 Jun 2024 00:05:05 +0400 Subject: [PATCH 04/13] In Process : check array and add list implementation --- ProjectCruiser/AbstractCompany.cs | 70 ++++++++++ ProjectCruiser/ArrayGenObj.cs | 94 +++++++++++++ ProjectCruiser/ICollectionGenObj.cs | 24 ++++ ProjectCruiser/OceanForm1.cs | 13 ++ ProjectCruiser/Program.cs | 3 +- ProjectCruiser/ServiceForm2.Designer.cs | 172 ++++++++++++++++++++++++ ProjectCruiser/ServiceForm2.cs | 137 +++++++++++++++++++ ProjectCruiser/ServiceForm2.resx | 120 +++++++++++++++++ ProjectCruiser/ShipSharingService.cs | 68 ++++++++++ 9 files changed, 700 insertions(+), 1 deletion(-) create mode 100644 ProjectCruiser/AbstractCompany.cs create mode 100644 ProjectCruiser/ArrayGenObj.cs create mode 100644 ProjectCruiser/ICollectionGenObj.cs create mode 100644 ProjectCruiser/ServiceForm2.Designer.cs create mode 100644 ProjectCruiser/ServiceForm2.cs create mode 100644 ProjectCruiser/ServiceForm2.resx create mode 100644 ProjectCruiser/ShipSharingService.cs diff --git a/ProjectCruiser/AbstractCompany.cs b/ProjectCruiser/AbstractCompany.cs new file mode 100644 index 0000000..e9b42e3 --- /dev/null +++ b/ProjectCruiser/AbstractCompany.cs @@ -0,0 +1,70 @@ +using ProjectCruiser.DrawningSamples; +namespace ProjectCruiser; + +/// Абстракция компании, хранящий коллекцию автомобилей +/// +public abstract class AbstractCompany +{ + // Размеры места + protected readonly int _placeSizeWidth = 312; // ширина + + protected readonly int _placeSizeHeight = 56; // высота + + // Ширина окна + protected readonly int _pictureWidth; + // Высота окна + protected readonly int _pictureHeight; + + // Коллекция автомобилей + protected ICollectionGenObj? _collection = null; + private int GetMaxCount => _pictureWidth * _pictureHeight / + (_placeSizeWidth * _placeSizeHeight); + + public AbstractCompany(int picWidth, int picHeight, + ICollectionGenObj? collection) + { + _pictureWidth = picWidth; + _pictureHeight = picHeight; + _collection = collection; + _collection.SetMaxCount = GetMaxCount; + } + + // Перегрузка оператора сложения для класса + // [ ! ] insted of bool: + public static int operator +(AbstractCompany cmp, + DrawningBase trasport) => (cmp._collection.Insert(trasport)); + + // Перегрузка оператора удаления для класса + public static DrawningBase operator -(AbstractCompany cmp, + int pos) => (cmp._collection.Remove(pos)); + + // Получение случайного объекта из коллекции + public DrawningBase? GetRandomObject() + { + Random rnd = new(); + return _collection?.GetItem(rnd.Next(GetMaxCount)); + } + + // Вывод всей коллекции + public Bitmap? Show() + { + Bitmap bitmap = new(_pictureWidth, _pictureHeight); + Graphics graphics = Graphics.FromImage(bitmap); + DrawBackground(graphics); + SetObjectsPosition(); + for (int i = 0; i < (_collection?.Count ?? 0); ++i) + { + DrawningBase? obj = _collection?.GetItem(i); + obj?.DrawTransport(graphics); + } + return bitmap; + } + + + // Вывод заднего фона + protected abstract void DrawBackground(Graphics g); + + // Расстановка объектов + protected abstract void SetObjectsPosition(); +} + diff --git a/ProjectCruiser/ArrayGenObj.cs b/ProjectCruiser/ArrayGenObj.cs new file mode 100644 index 0000000..a20cf25 --- /dev/null +++ b/ProjectCruiser/ArrayGenObj.cs @@ -0,0 +1,94 @@ +namespace ProjectCruiser; + +public class ArrayGenObj : ICollectionGenObj + where T : class +{ + // Массив объектов, которые храним + private T?[] _collection; + public int Count => _collection.Length; + public int SetMaxCount + { + set + { + if (value > 0) + { + if (_collection.Length > 0) Array.Resize(ref _collection, value); + else _collection = new T?[value]; + } + } + } + + // public int SetMaxCount { set { if (value > 0) { _collection = new T?[value]; } } } + + public ArrayGenObj() + { + _collection = Array.Empty(); + } + + // methods : + + public T? GetItem(int index) + { + if (index > Count || index < 0) + { + return null; + } + return _collection[index]; + } + + public int Insert(T? item) + { + // any empty place + for (int i = 0; i < Count; i++) + { + if (_collection[i] == null) + { + _collection[i] = item; + return i; + } + } + return -1; + } + + public int Insert(T? item, int index) + { + if (_collection[index] == null) + { + _collection[index] = item; + return index; + } + + else + { + int min_diff = 100, min_index = 100; + + for (int i = 0; i < Count; i++) + { + if (_collection[i] == null + && min_diff > Math.Abs(index - i)) + { + min_diff = Math.Abs(index - i); + min_index = i; + } + } + + _collection[min_index] = item; + return min_index; + } + + return -1; + } + + public T? Remove(int index) + { + T? item; + if (index < Count && index >= 0) + { + item = _collection[index]; + _collection[index] = null; + return item; + } + return null; + } +} + diff --git a/ProjectCruiser/ICollectionGenObj.cs b/ProjectCruiser/ICollectionGenObj.cs new file mode 100644 index 0000000..9012d74 --- /dev/null +++ b/ProjectCruiser/ICollectionGenObj.cs @@ -0,0 +1,24 @@ +namespace ProjectCruiser; + +public interface ICollectionGenObj where T : class +{ + // Кол-во объектов в коллекции + int Count { get; } + + // Установка max кол-ва элементов + int SetMaxCount { set; } + + /// Добавление объекта в коллекцию + /// Добавляемый объект + /// true - вставка прошла удачно, false - вставка не удалась + int Insert(T obj); + int Insert(T obj, int position); + + /// Удаление объекта из коллекции с конкретной позиции + /// Позиция + /// true - удаление прошло удачно, false - удаление не удалось + T? Remove(int position); + + // Получение объекта по позиции + T? GetItem(int position); +} diff --git a/ProjectCruiser/OceanForm1.cs b/ProjectCruiser/OceanForm1.cs index f214473..fbb09fb 100644 --- a/ProjectCruiser/OceanForm1.cs +++ b/ProjectCruiser/OceanForm1.cs @@ -11,6 +11,19 @@ namespace ProjectCruiser // Стратегия перемещения private AbstractStrategy? _strategy; + // Получение объекта + public DrawningBase SetShip + { + set + { + _drawningCruiser = value; + _drawningCruiser.SetPictureSize(pictureBoxCr.Width, pictureBoxCr.Height); + comboBoxStrategy.Enabled = true; + _strategy = null; + Draw(); + } + } + public OceanForm1() { InitializeComponent(); diff --git a/ProjectCruiser/Program.cs b/ProjectCruiser/Program.cs index 5669fde..faeb072 100644 --- a/ProjectCruiser/Program.cs +++ b/ProjectCruiser/Program.cs @@ -11,7 +11,8 @@ namespace ProjectCruiser // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new OceanForm1()); + Application.Run(new ServiceForm2()); + // -> OceanForm1() inside* } } } \ No newline at end of file diff --git a/ProjectCruiser/ServiceForm2.Designer.cs b/ProjectCruiser/ServiceForm2.Designer.cs new file mode 100644 index 0000000..c161352 --- /dev/null +++ b/ProjectCruiser/ServiceForm2.Designer.cs @@ -0,0 +1,172 @@ +namespace ProjectCruiser +{ + partial class ServiceForm2 + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + comboBoxArrList = new ComboBox(); + btnAddBase = new Button(); + groupBox = new GroupBox(); + btnUpdate = new Button(); + btnTest = new Button(); + btnDelete = new Button(); + maskedTextBoxPosition = new MaskedTextBox(); + btnAddCruiser = new Button(); + pictureBox = new PictureBox(); + groupBox.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); + SuspendLayout(); + // + // comboBoxArrList + // + comboBoxArrList.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + comboBoxArrList.FormattingEnabled = true; + comboBoxArrList.Location = new Point(17, 54); + comboBoxArrList.Name = "comboBoxArrList"; + comboBoxArrList.Size = new Size(242, 40); + comboBoxArrList.TabIndex = 0; + comboBoxArrList.SelectedIndexChanged += SelectorCompany_SelectedIndexChanged; + // + // btnAddBase + // + btnAddBase.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + btnAddBase.Location = new Point(17, 561); + btnAddBase.Name = "btnAddBase"; + btnAddBase.Size = new Size(242, 46); + btnAddBase.TabIndex = 1; + btnAddBase.Text = "Add ship"; + btnAddBase.UseVisualStyleBackColor = true; + btnAddBase.Click += btnAddBase_Click; + // + // groupBox + // + groupBox.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + groupBox.Controls.Add(btnUpdate); + groupBox.Controls.Add(btnTest); + groupBox.Controls.Add(btnDelete); + groupBox.Controls.Add(maskedTextBoxPosition); + groupBox.Controls.Add(btnAddCruiser); + groupBox.Controls.Add(btnAddBase); + groupBox.Controls.Add(comboBoxArrList); + groupBox.Location = new Point(1006, 12); + groupBox.Name = "groupBox"; + groupBox.Size = new Size(274, 938); + groupBox.TabIndex = 2; + groupBox.TabStop = false; + groupBox.Text = "Tool panel"; + // + // btnUpdate + // + btnUpdate.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + btnUpdate.Location = new Point(17, 865); + btnUpdate.Name = "btnUpdate"; + btnUpdate.Size = new Size(242, 46); + btnUpdate.TabIndex = 6; + btnUpdate.Text = "Update"; + btnUpdate.UseVisualStyleBackColor = true; + btnUpdate.Click += btnRefresh_Click; + // + // btnTest + // + btnTest.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + btnTest.Location = new Point(17, 795); + btnTest.Name = "btnTest"; + btnTest.Size = new Size(242, 64); + btnTest.TabIndex = 5; + btnTest.Text = "Choose for testing"; + btnTest.UseVisualStyleBackColor = true; + btnTest.Click += btnChooseforTest_Click; + // + // btnDelete + // + btnDelete.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + btnDelete.Location = new Point(17, 732); + btnDelete.Name = "btnDelete"; + btnDelete.Size = new Size(242, 46); + btnDelete.TabIndex = 4; + btnDelete.Text = "Delete"; + btnDelete.UseVisualStyleBackColor = true; + btnDelete.Click += btnRemoveCar_Click; + // + // maskedTextBoxPosition + // + maskedTextBoxPosition.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + maskedTextBoxPosition.Location = new Point(17, 682); + maskedTextBoxPosition.Mask = "00"; + maskedTextBoxPosition.Name = "maskedTextBoxPosition"; + maskedTextBoxPosition.Size = new Size(242, 39); + maskedTextBoxPosition.TabIndex = 3; + maskedTextBoxPosition.ValidatingType = typeof(int); + // + // btnAddCruiser + // + btnAddCruiser.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + btnAddCruiser.Location = new Point(17, 613); + btnAddCruiser.Name = "btnAddCruiser"; + btnAddCruiser.Size = new Size(242, 46); + btnAddCruiser.TabIndex = 2; + btnAddCruiser.Text = "Add cruiser"; + btnAddCruiser.UseVisualStyleBackColor = true; + btnAddCruiser.Click += btnAddAdvanced_Click; + // + // pictureBox + // + pictureBox.Dock = DockStyle.Left; + pictureBox.Location = new Point(0, 0); + pictureBox.Name = "pictureBox"; + pictureBox.Size = new Size(988, 959); + pictureBox.TabIndex = 3; + pictureBox.TabStop = false; + // + // ServiceForm2 + // + AutoScaleDimensions = new SizeF(13F, 32F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(1292, 959); + Controls.Add(pictureBox); + Controls.Add(groupBox); + Name = "ServiceForm2"; + Text = "ServiceForm2"; + groupBox.ResumeLayout(false); + groupBox.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + ResumeLayout(false); + } + + #endregion + + private ComboBox comboBoxArrList; + private Button btnAddBase; + private GroupBox groupBox; + private Button btnAddCruiser; + private Button btnUpdate; + private Button btnTest; + private Button btnDelete; + private MaskedTextBox maskedTextBoxPosition; + private PictureBox pictureBox; + } +} \ No newline at end of file diff --git a/ProjectCruiser/ServiceForm2.cs b/ProjectCruiser/ServiceForm2.cs new file mode 100644 index 0000000..3861559 --- /dev/null +++ b/ProjectCruiser/ServiceForm2.cs @@ -0,0 +1,137 @@ +using System.Windows.Forms; +using ProjectCruiser.DrawningSamples; +namespace ProjectCruiser; + +public partial class ServiceForm2 : Form +{ + // Компания + private AbstractCompany? _company = null; + public ServiceForm2() + { + InitializeComponent(); + } + + // Выбор компании + private void SelectorCompany_SelectedIndexChanged(object sender, EventArgs e) + { + switch (comboBoxArrList.Text) + { + case "Storage": + _company = new ShipSharingService(pictureBox.Width, pictureBox.Height, + new ArrayGenObj()); + break; + } + } + + // Color picker + private static Color pickColor(Random r) + { + Color cl = Color.FromArgb(r.Next(0, 256), r.Next(0, 256), r.Next(0, 256)); + ColorDialog dialog = new(); + + if (dialog.ShowDialog() == DialogResult.OK) + { cl = dialog.Color; } + + return cl; + } + + // Добавление обычного корабля + private void btnAddBase_Click(object sender, EventArgs e) => + CreateObject(nameof(DrawningBase)); + + // Добавление продвинутого + private void btnAddAdvanced_Click(object sender, EventArgs e) => + CreateObject(nameof(DrawningCruiser)); + + // Создание объекта класса-перемещения + private void CreateObject(string type) + { + if (_company == null) + { + return; + } + Random random = new(); + DrawningBase drawningCar; + + switch (type) + { + case nameof(DrawningBase): + drawningCar = new DrawningBase(random.Next(100, 300), + random.Next(1000, 3000), pickColor(random)); + break; + + case nameof(DrawningCruiser): + // (TODO) вызов диалогового окна для выбора цвета >>> + drawningCar = new DrawningCruiser(random.Next(100, 300), + random.Next(1000, 3000), pickColor(random), pickColor(random), + Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2))); + break; + default: + return; + } + if (_company + drawningCar > 0) + { + MessageBox.Show("> Object was added"); + pictureBox.Image = _company.Show(); + } + else + { + MessageBox.Show("[!] Failed to add object"); + } + } + + // Удаление объекта + private void btnRemoveCar_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) + || _company == null) return; + + if (MessageBox.Show("[*] Remove object: Are you sure?", "Remove", + MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) return; + int pos = Convert.ToInt32(maskedTextBoxPosition.Text); + + if (_company - Convert.ToInt32(maskedTextBoxPosition.Text) != null) + { + MessageBox.Show("> Object was removed"); + pictureBox.Image = _company.Show(); + } + else MessageBox.Show("[!] Failed to remove object"); + } + + // Передача объекта в другую форму + private void btnChooseforTest_Click(object sender, EventArgs e) + { + if (_company == null) + { + return; + } + DrawningBase? car = null; + int counter = 100; + while (car == null) + { + car = _company.GetRandomObject(); + counter--; + if (counter <= 0) + { + break; + } + } + if (car == null) + { + return; + } + + OceanForm1 form = new() { SetShip = car }; + form.ShowDialog(); + } + + // Перерисовка коллекции + private void btnRefresh_Click(object sender, EventArgs e) + { + if (_company == null) + { + return; + } + pictureBox.Image = _company.Show(); + } +} diff --git a/ProjectCruiser/ServiceForm2.resx b/ProjectCruiser/ServiceForm2.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/ProjectCruiser/ServiceForm2.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/ProjectCruiser/ShipSharingService.cs b/ProjectCruiser/ShipSharingService.cs new file mode 100644 index 0000000..1cd69fe --- /dev/null +++ b/ProjectCruiser/ShipSharingService.cs @@ -0,0 +1,68 @@ +using ProjectCruiser.DrawningSamples; +namespace ProjectCruiser; + +public class ShipSharingService : AbstractCompany +{ + protected int MaxInRow { get; private set; } + protected int MaxInColon { get; private set; } + + private int fromBorder = 20, fromCeiling = 20, between = 30; + + public ShipSharingService(int picWidth, int picHeight, + ICollectionGenObj collection) + : base(picWidth, picHeight, collection) + { + MaxInRow = (picWidth - fromBorder - fromCeiling) + / (_placeSizeWidth + between); + MaxInColon = (picHeight - fromBorder - fromCeiling) + / _placeSizeHeight; + } + + protected override void DrawBackground(Graphics g) + { + Pen pen = new(Color.Black, 2); + + int currentH = 10, currentW = 10; + + for (int i = 0; i < MaxInRow; i++) + { + currentH = 10; + for (int j = 0; j < MaxInColon; j++) + { + g.DrawLine(pen, currentW + _placeSizeWidth, currentH - 1, + currentW - 1, currentH - 1); + g.DrawLine(pen, currentW - 1, currentH - 1, currentW - 1, + currentH + _placeSizeHeight); + + currentH += _placeSizeHeight + 1; + } + currentW += _placeSizeWidth + between; + } + } + + protected override void SetObjectsPosition() + { + int index_collection = 0; + int newX = fromBorder, newY = fromCeiling; + + if (_collection != null) + { + for (int i = 0; i < MaxInColon; ++i) + { + newX = fromBorder; + for (int j = 0; j < MaxInRow; ++j) + { + if (_collection.GetItem(index_collection) != null) + { + _collection.GetItem(index_collection).SetPictureSize(_pictureWidth, _pictureHeight); + _collection.GetItem(index_collection).SetPosition(newX, newY); + newX += _placeSizeWidth + between; + index_collection++; + } + } + newY += _placeSizeHeight + 2; + } + } + } +} + -- 2.25.1 From a6ff38c3e47c60c71aaf317598e191b5ecd70aa9 Mon Sep 17 00:00:00 2001 From: DelphyAlmond Date: Thu, 13 Jun 2024 10:57:01 +0400 Subject: [PATCH 05/13] polymorphism --- .../DrawningSamples/DrawningCruiser.cs | 28 +++++++------------ ProjectCruiser/Entities/EntityCruiser.cs | 8 +++--- ProjectCruiser/OceanForm1.cs | 5 ++-- ProjectCruiser/ServiceForm2.Designer.cs | 25 +++++++++-------- ProjectCruiser/ServiceForm2.cs | 7 +++-- ProjectCruiser/ShipSharingService.cs | 19 +++++++------ 6 files changed, 44 insertions(+), 48 deletions(-) diff --git a/ProjectCruiser/DrawningSamples/DrawningCruiser.cs b/ProjectCruiser/DrawningSamples/DrawningCruiser.cs index 90127e5..4f3f56e 100644 --- a/ProjectCruiser/DrawningSamples/DrawningCruiser.cs +++ b/ProjectCruiser/DrawningSamples/DrawningCruiser.cs @@ -6,11 +6,11 @@ public class DrawningCruiser : DrawningBase { // Инициализация свойств (все параметры класса (сущности)) public DrawningCruiser(int speed, double weight, Color bodyColor, - Color additionalColor, bool pads, bool hangar) : base(302, 42) + Color additionalColor, bool hangars) : base(302, 42) // all additional featchures 'inside' object, so size remains { EntityTransport = new EntityCruiser(speed, weight, - bodyColor, additionalColor, pads, hangar); + bodyColor, additionalColor, hangars); } public override void DrawTransport(Graphics g) @@ -31,24 +31,16 @@ public class DrawningCruiser : DrawningBase base.DrawTransport(g); - // вертолетная площадка - if (ship.HelicopterPads) - { - g.DrawEllipse(pen, _startPosX.Value + 170, _startPosY.Value + 11, 20, 20); - g.FillEllipse(PadBrush, _startPosX.Value + 170, _startPosY.Value + 11, 20, 20); - } + // вертолетная площадка - default TRUE now + g.DrawEllipse(pen, _startPosX.Value + 170, _startPosY.Value + 11, 20, 20); + g.FillEllipse(PadBrush, _startPosX.Value + 170, _startPosY.Value + 11, 20, 20); - // ангар - if (ship.Hangar) + // ангар(ы) + if (ship.Hangars) { - int n = EntityTransport.values[2]; - if (n == 1) g.FillRectangle(additionalBrush, _startPosX.Value + 250, _startPosY.Value + 20, 14, 7); - - else - { - g.FillRectangle(additionalBrush, _startPosX.Value + 80, _startPosY.Value + 10, 10, 20); - g.FillRectangle(additionalBrush, _startPosX.Value + 70, _startPosY.Value + 12, 8, 12); - } + g.FillRectangle(additionalBrush, _startPosX.Value + 80, _startPosY.Value + 10, 10, 20); + g.FillRectangle(additionalBrush, _startPosX.Value + 70, _startPosY.Value + 12, 8, 12); } + else g.FillRectangle(additionalBrush, _startPosX.Value + 250, _startPosY.Value + 20, 14, 7); } } diff --git a/ProjectCruiser/Entities/EntityCruiser.cs b/ProjectCruiser/Entities/EntityCruiser.cs index e251e02..514f8e8 100644 --- a/ProjectCruiser/Entities/EntityCruiser.cs +++ b/ProjectCruiser/Entities/EntityCruiser.cs @@ -6,14 +6,14 @@ public class EntityCruiser : EntityBase // признаки (наличия) public bool HelicopterPads { get; private set; } // вертолетная площадка - public bool Hangar { get; private set; } // ангар + public bool Hangars { get; private set; } // ангар public EntityCruiser(int speed, double weight, Color mainc, - Color additionalColor, bool pads, bool hangar) + Color additionalColor, bool hangars) : base(speed, weight, mainc) { AdditionalColor = additionalColor; - HelicopterPads = pads; - Hangar = hangar; + // HelicopterPads = pads; - default TRUE now for Advanced obj + Hangars = hangars; } } diff --git a/ProjectCruiser/OceanForm1.cs b/ProjectCruiser/OceanForm1.cs index fbb09fb..e8b217f 100644 --- a/ProjectCruiser/OceanForm1.cs +++ b/ProjectCruiser/OceanForm1.cs @@ -64,10 +64,11 @@ namespace ProjectCruiser break; case nameof(DrawningCruiser): - _drawningCruiser = new DrawningCruiser(random.Next(100, 300), random.Next(1000, 3000), + _drawningCruiser = new DrawningCruiser( + random.Next(100, 300), random.Next(1000, 3000), Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), - Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2))); + Convert.ToBoolean(random.Next(0, 2))); break; default: diff --git a/ProjectCruiser/ServiceForm2.Designer.cs b/ProjectCruiser/ServiceForm2.Designer.cs index c161352..8990b79 100644 --- a/ProjectCruiser/ServiceForm2.Designer.cs +++ b/ProjectCruiser/ServiceForm2.Designer.cs @@ -45,9 +45,10 @@ // comboBoxArrList.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; comboBoxArrList.FormattingEnabled = true; + comboBoxArrList.Items.AddRange(new object[] { "Storage" }); comboBoxArrList.Location = new Point(17, 54); comboBoxArrList.Name = "comboBoxArrList"; - comboBoxArrList.Size = new Size(242, 40); + comboBoxArrList.Size = new Size(268, 40); comboBoxArrList.TabIndex = 0; comboBoxArrList.SelectedIndexChanged += SelectorCompany_SelectedIndexChanged; // @@ -56,7 +57,7 @@ btnAddBase.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; btnAddBase.Location = new Point(17, 561); btnAddBase.Name = "btnAddBase"; - btnAddBase.Size = new Size(242, 46); + btnAddBase.Size = new Size(268, 46); btnAddBase.TabIndex = 1; btnAddBase.Text = "Add ship"; btnAddBase.UseVisualStyleBackColor = true; @@ -72,9 +73,9 @@ groupBox.Controls.Add(btnAddCruiser); groupBox.Controls.Add(btnAddBase); groupBox.Controls.Add(comboBoxArrList); - groupBox.Location = new Point(1006, 12); + groupBox.Location = new Point(1437, 12); groupBox.Name = "groupBox"; - groupBox.Size = new Size(274, 938); + groupBox.Size = new Size(300, 938); groupBox.TabIndex = 2; groupBox.TabStop = false; groupBox.Text = "Tool panel"; @@ -84,7 +85,7 @@ btnUpdate.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; btnUpdate.Location = new Point(17, 865); btnUpdate.Name = "btnUpdate"; - btnUpdate.Size = new Size(242, 46); + btnUpdate.Size = new Size(268, 46); btnUpdate.TabIndex = 6; btnUpdate.Text = "Update"; btnUpdate.UseVisualStyleBackColor = true; @@ -95,7 +96,7 @@ btnTest.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; btnTest.Location = new Point(17, 795); btnTest.Name = "btnTest"; - btnTest.Size = new Size(242, 64); + btnTest.Size = new Size(268, 64); btnTest.TabIndex = 5; btnTest.Text = "Choose for testing"; btnTest.UseVisualStyleBackColor = true; @@ -106,19 +107,19 @@ btnDelete.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; btnDelete.Location = new Point(17, 732); btnDelete.Name = "btnDelete"; - btnDelete.Size = new Size(242, 46); + btnDelete.Size = new Size(268, 46); btnDelete.TabIndex = 4; btnDelete.Text = "Delete"; btnDelete.UseVisualStyleBackColor = true; btnDelete.Click += btnRemoveCar_Click; // // maskedTextBoxPosition - // + // maskedTextBoxPosition.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; maskedTextBoxPosition.Location = new Point(17, 682); maskedTextBoxPosition.Mask = "00"; maskedTextBoxPosition.Name = "maskedTextBoxPosition"; - maskedTextBoxPosition.Size = new Size(242, 39); + maskedTextBoxPosition.Size = new Size(268, 39); maskedTextBoxPosition.TabIndex = 3; maskedTextBoxPosition.ValidatingType = typeof(int); // @@ -127,7 +128,7 @@ btnAddCruiser.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; btnAddCruiser.Location = new Point(17, 613); btnAddCruiser.Name = "btnAddCruiser"; - btnAddCruiser.Size = new Size(242, 46); + btnAddCruiser.Size = new Size(268, 46); btnAddCruiser.TabIndex = 2; btnAddCruiser.Text = "Add cruiser"; btnAddCruiser.UseVisualStyleBackColor = true; @@ -138,7 +139,7 @@ pictureBox.Dock = DockStyle.Left; pictureBox.Location = new Point(0, 0); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(988, 959); + pictureBox.Size = new Size(1417, 959); pictureBox.TabIndex = 3; pictureBox.TabStop = false; // @@ -146,7 +147,7 @@ // AutoScaleDimensions = new SizeF(13F, 32F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1292, 959); + ClientSize = new Size(1749, 959); Controls.Add(pictureBox); Controls.Add(groupBox); Name = "ServiceForm2"; diff --git a/ProjectCruiser/ServiceForm2.cs b/ProjectCruiser/ServiceForm2.cs index 3861559..b17ae80 100644 --- a/ProjectCruiser/ServiceForm2.cs +++ b/ProjectCruiser/ServiceForm2.cs @@ -5,10 +5,11 @@ namespace ProjectCruiser; public partial class ServiceForm2 : Form { // Компания - private AbstractCompany? _company = null; + private AbstractCompany? _company; public ServiceForm2() { InitializeComponent(); + _company = null; } // Выбор компании @@ -64,12 +65,12 @@ public partial class ServiceForm2 : Form // (TODO) вызов диалогового окна для выбора цвета >>> drawningCar = new DrawningCruiser(random.Next(100, 300), random.Next(1000, 3000), pickColor(random), pickColor(random), - Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2))); + Convert.ToBoolean(random.Next(0, 2))); break; default: return; } - if (_company + drawningCar > 0) + if (_company + drawningCar != -1) { MessageBox.Show("> Object was added"); pictureBox.Image = _company.Show(); diff --git a/ProjectCruiser/ShipSharingService.cs b/ProjectCruiser/ShipSharingService.cs index 1cd69fe..e0098d4 100644 --- a/ProjectCruiser/ShipSharingService.cs +++ b/ProjectCruiser/ShipSharingService.cs @@ -22,17 +22,18 @@ public class ShipSharingService : AbstractCompany { Pen pen = new(Color.Black, 2); - int currentH = 10, currentW = 10; + int currentH = fromCeiling, currentW = fromBorder; for (int i = 0; i < MaxInRow; i++) { - currentH = 10; + currentH = fromCeiling; for (int j = 0; j < MaxInColon; j++) { - g.DrawLine(pen, currentW + _placeSizeWidth, currentH - 1, - currentW - 1, currentH - 1); - g.DrawLine(pen, currentW - 1, currentH - 1, currentW - 1, - currentH + _placeSizeHeight); + g.DrawLine(pen, currentW + _placeSizeWidth, + currentH, currentW, currentH); + + g.DrawLine(pen, currentW, currentH, + currentW, currentH + _placeSizeHeight); currentH += _placeSizeHeight + 1; } @@ -43,20 +44,20 @@ public class ShipSharingService : AbstractCompany protected override void SetObjectsPosition() { int index_collection = 0; - int newX = fromBorder, newY = fromCeiling; + int newX = fromBorder + 6, newY = fromCeiling + 6; if (_collection != null) { for (int i = 0; i < MaxInColon; ++i) { - newX = fromBorder; + newX = fromBorder + 2; for (int j = 0; j < MaxInRow; ++j) { if (_collection.GetItem(index_collection) != null) { _collection.GetItem(index_collection).SetPictureSize(_pictureWidth, _pictureHeight); _collection.GetItem(index_collection).SetPosition(newX, newY); - newX += _placeSizeWidth + between; + newX += _placeSizeWidth + between + 2; index_collection++; } } -- 2.25.1 From b822f2ef79eb8f552329bf0c320d7557000b433a Mon Sep 17 00:00:00 2001 From: DelphyAlmond Date: Thu, 13 Jun 2024 13:58:43 +0400 Subject: [PATCH 06/13] In process : connect buttons, list-&-text boxes --- ProjectCruiser/ListGenObj.cs | 68 +++++++++ ProjectCruiser/ServiceForm2.Designer.cs | 178 ++++++++++++++++++++---- ProjectCruiser/ServiceForm2.cs | 12 +- 3 files changed, 227 insertions(+), 31 deletions(-) create mode 100644 ProjectCruiser/ListGenObj.cs diff --git a/ProjectCruiser/ListGenObj.cs b/ProjectCruiser/ListGenObj.cs new file mode 100644 index 0000000..c945997 --- /dev/null +++ b/ProjectCruiser/ListGenObj.cs @@ -0,0 +1,68 @@ +using System; +using System.Reflection; + +namespace ProjectCruiser; + +// Параметризованный набор объектов +public class ListGenericObjects : ICollectionGenObj + where T : class +{ + // Список объектов, которые храним + private readonly List _collection; + + // Максимально допустимое число объектов в списке + private int _maxCount; + public int Count => _collection.Count; + + public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } + + public ListGenericObjects() + { + _collection = new(); + } + + public T? GetItem(int position) + { + if (position > _maxCount - 1 || position < 0) + { + return null; + } + + return _collection[position]; + } + + public int Insert(T obj) + { + if (Count + 1 < _maxCount || obj == null) + { + return -1; + } + _collection.Add(obj); + return Count; + } + + public int Insert(T obj, int position) + { + if (position >= _maxCount || position < 0 || + _collection[position] != null) + { + return -1; + } + + _collection.Insert(position, obj); + return position; + } + + public T? Remove(int position) + { + if (position >= Count || position < 0) + // on the other positions items don't exist + { + return null; + } + + T? item = _collection[position]; + _collection.RemoveAt(position); + return item; + } +} diff --git a/ProjectCruiser/ServiceForm2.Designer.cs b/ProjectCruiser/ServiceForm2.Designer.cs index 8990b79..a9db303 100644 --- a/ProjectCruiser/ServiceForm2.Designer.cs +++ b/ProjectCruiser/ServiceForm2.Designer.cs @@ -37,8 +37,20 @@ maskedTextBoxPosition = new MaskedTextBox(); btnAddCruiser = new Button(); pictureBox = new PictureBox(); + companyPanel = new Panel(); + label = new Label(); + maskedTxtBoxCName = new MaskedTextBox(); + rBtnArray = new RadioButton(); + rBtnList = new RadioButton(); + btnAddCollection = new Button(); + listBox = new ListBox(); + btnDeleteCollection = new Button(); + btnCreateCompany = new Button(); + toolPanel = new Panel(); groupBox.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); + companyPanel.SuspendLayout(); + toolPanel.SuspendLayout(); SuspendLayout(); // // comboBoxArrList @@ -46,18 +58,18 @@ comboBoxArrList.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; comboBoxArrList.FormattingEnabled = true; comboBoxArrList.Items.AddRange(new object[] { "Storage" }); - comboBoxArrList.Location = new Point(17, 54); + comboBoxArrList.Location = new Point(17, 41); comboBoxArrList.Name = "comboBoxArrList"; - comboBoxArrList.Size = new Size(268, 40); + comboBoxArrList.Size = new Size(243, 40); comboBoxArrList.TabIndex = 0; comboBoxArrList.SelectedIndexChanged += SelectorCompany_SelectedIndexChanged; // // btnAddBase // btnAddBase.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - btnAddBase.Location = new Point(17, 561); + btnAddBase.Location = new Point(17, 13); btnAddBase.Name = "btnAddBase"; - btnAddBase.Size = new Size(268, 46); + btnAddBase.Size = new Size(192, 43); btnAddBase.TabIndex = 1; btnAddBase.Text = "Add ship"; btnAddBase.UseVisualStyleBackColor = true; @@ -66,16 +78,12 @@ // groupBox // groupBox.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - groupBox.Controls.Add(btnUpdate); - groupBox.Controls.Add(btnTest); - groupBox.Controls.Add(btnDelete); - groupBox.Controls.Add(maskedTextBoxPosition); - groupBox.Controls.Add(btnAddCruiser); - groupBox.Controls.Add(btnAddBase); + groupBox.Controls.Add(toolPanel); + groupBox.Controls.Add(btnCreateCompany); groupBox.Controls.Add(comboBoxArrList); - groupBox.Location = new Point(1437, 12); + groupBox.Location = new Point(1402, 12); groupBox.Name = "groupBox"; - groupBox.Size = new Size(300, 938); + groupBox.Size = new Size(275, 986); groupBox.TabIndex = 2; groupBox.TabStop = false; groupBox.Text = "Tool panel"; @@ -83,9 +91,9 @@ // btnUpdate // btnUpdate.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - btnUpdate.Location = new Point(17, 865); + btnUpdate.Location = new Point(17, 315); btnUpdate.Name = "btnUpdate"; - btnUpdate.Size = new Size(268, 46); + btnUpdate.Size = new Size(192, 49); btnUpdate.TabIndex = 6; btnUpdate.Text = "Update"; btnUpdate.UseVisualStyleBackColor = true; @@ -94,20 +102,20 @@ // btnTest // btnTest.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - btnTest.Location = new Point(17, 795); + btnTest.Location = new Point(17, 224); btnTest.Name = "btnTest"; - btnTest.Size = new Size(268, 64); + btnTest.Size = new Size(192, 85); btnTest.TabIndex = 5; - btnTest.Text = "Choose for testing"; + btnTest.Text = "Choose\r\nfor testing"; btnTest.UseVisualStyleBackColor = true; btnTest.Click += btnChooseforTest_Click; // // btnDelete // btnDelete.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - btnDelete.Location = new Point(17, 732); + btnDelete.Location = new Point(17, 170); btnDelete.Name = "btnDelete"; - btnDelete.Size = new Size(268, 46); + btnDelete.Size = new Size(192, 48); btnDelete.TabIndex = 4; btnDelete.Text = "Delete"; btnDelete.UseVisualStyleBackColor = true; @@ -116,19 +124,19 @@ // maskedTextBoxPosition // maskedTextBoxPosition.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - maskedTextBoxPosition.Location = new Point(17, 682); + maskedTextBoxPosition.Location = new Point(17, 119); maskedTextBoxPosition.Mask = "00"; maskedTextBoxPosition.Name = "maskedTextBoxPosition"; - maskedTextBoxPosition.Size = new Size(268, 39); + maskedTextBoxPosition.Size = new Size(192, 39); maskedTextBoxPosition.TabIndex = 3; maskedTextBoxPosition.ValidatingType = typeof(int); // // btnAddCruiser // btnAddCruiser.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - btnAddCruiser.Location = new Point(17, 613); + btnAddCruiser.Location = new Point(17, 62); btnAddCruiser.Name = "btnAddCruiser"; - btnAddCruiser.Size = new Size(268, 46); + btnAddCruiser.Size = new Size(192, 51); btnAddCruiser.TabIndex = 2; btnAddCruiser.Text = "Add cruiser"; btnAddCruiser.UseVisualStyleBackColor = true; @@ -139,22 +147,130 @@ pictureBox.Dock = DockStyle.Left; pictureBox.Location = new Point(0, 0); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(1417, 959); + pictureBox.Size = new Size(1385, 1007); pictureBox.TabIndex = 3; pictureBox.TabStop = false; // + // companyPanel + // + companyPanel.Controls.Add(btnDeleteCollection); + companyPanel.Controls.Add(listBox); + companyPanel.Controls.Add(btnAddCollection); + companyPanel.Controls.Add(rBtnList); + companyPanel.Controls.Add(rBtnArray); + companyPanel.Controls.Add(maskedTxtBoxCName); + companyPanel.Controls.Add(label); + companyPanel.Location = new Point(1419, 101); + companyPanel.Name = "panel1"; + companyPanel.Size = new Size(243, 429); + companyPanel.TabIndex = 7; + // + // label + // + label.AutoSize = true; + label.Location = new Point(29, 6); + label.Name = "label"; + label.Size = new Size(188, 32); + label.TabIndex = 0; + label.Text = "Collection name"; + // + // maskedTxtBoxCName + // + maskedTxtBoxCName.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + maskedTxtBoxCName.Location = new Point(16, 43); + maskedTxtBoxCName.Name = "maskedTextBox1"; + maskedTxtBoxCName.Size = new Size(214, 39); + maskedTxtBoxCName.TabIndex = 7; + // + // rBtnArray + // + rBtnArray.AutoSize = true; + rBtnArray.Location = new Point(16, 88); + rBtnArray.Name = "rBtnArray"; + rBtnArray.Size = new Size(100, 36); + rBtnArray.TabIndex = 8; + rBtnArray.TabStop = true; + rBtnArray.Text = "Array"; + rBtnArray.UseVisualStyleBackColor = true; + // + // rBtnList + // + rBtnList.AutoSize = true; + rBtnList.Location = new Point(150, 88); + rBtnList.Name = "rBtnList"; + rBtnList.Size = new Size(80, 36); + rBtnList.TabIndex = 9; + rBtnList.TabStop = true; + rBtnList.Text = "List"; + rBtnList.UseVisualStyleBackColor = true; + // + // btnAddCollection + // + btnAddCollection.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + btnAddCollection.Location = new Point(15, 130); + btnAddCollection.Name = "btnAddCollection"; + btnAddCollection.Size = new Size(214, 61); + btnAddCollection.TabIndex = 7; + btnAddCollection.Text = "Add Collection"; + btnAddCollection.UseVisualStyleBackColor = true; + // + // listBox1 + // + listBox.FormattingEnabled = true; + listBox.Location = new Point(16, 199); + listBox.Name = "listBox1"; + listBox.Size = new Size(214, 164); + listBox.TabIndex = 10; + // + // btnDeleteCollection + // + btnDeleteCollection.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + btnDeleteCollection.Location = new Point(15, 371); + btnDeleteCollection.Name = "btnDeleteCollection"; + btnDeleteCollection.Size = new Size(214, 43); + btnDeleteCollection.TabIndex = 11; + btnDeleteCollection.Text = "Remove Collection"; + btnDeleteCollection.UseVisualStyleBackColor = true; + // + // btnCreateCompany + // + btnCreateCompany.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + btnCreateCompany.Location = new Point(17, 526); + btnCreateCompany.Name = "btnCreateCompany"; + btnCreateCompany.Size = new Size(243, 61); + btnCreateCompany.TabIndex = 12; + btnCreateCompany.Text = "Create Company"; + btnCreateCompany.UseVisualStyleBackColor = true; + // + // toolPanel + // + toolPanel.Controls.Add(btnUpdate); + toolPanel.Controls.Add(btnTest); + toolPanel.Controls.Add(maskedTextBoxPosition); + toolPanel.Controls.Add(btnDelete); + toolPanel.Controls.Add(btnAddCruiser); + toolPanel.Controls.Add(btnAddBase); + toolPanel.Location = new Point(26, 596); + toolPanel.Name = "panel2"; + toolPanel.Size = new Size(226, 377); + toolPanel.TabIndex = 13; + // // ServiceForm2 // AutoScaleDimensions = new SizeF(13F, 32F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1749, 959); + ClientSize = new Size(1689, 1007); + Controls.Add(companyPanel); Controls.Add(pictureBox); Controls.Add(groupBox); Name = "ServiceForm2"; Text = "ServiceForm2"; groupBox.ResumeLayout(false); - groupBox.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + companyPanel.ResumeLayout(false); + companyPanel.PerformLayout(); + toolPanel.ResumeLayout(false); + toolPanel.PerformLayout(); ResumeLayout(false); } @@ -169,5 +285,15 @@ private Button btnDelete; private MaskedTextBox maskedTextBoxPosition; private PictureBox pictureBox; + private Panel companyPanel; + private RadioButton rBtnArray; + private MaskedTextBox maskedTxtBoxCName; + private Label label; + private RadioButton rBtnList; + private Button btnAddCollection; + private ListBox listBox; + private Button btnDeleteCollection; + private Button btnCreateCompany; + private Panel toolPanel; } } \ No newline at end of file diff --git a/ProjectCruiser/ServiceForm2.cs b/ProjectCruiser/ServiceForm2.cs index b17ae80..80ae0ad 100644 --- a/ProjectCruiser/ServiceForm2.cs +++ b/ProjectCruiser/ServiceForm2.cs @@ -24,14 +24,14 @@ public partial class ServiceForm2 : Form } } - // Color picker + // Color picker (default : random) private static Color pickColor(Random r) { - Color cl = Color.FromArgb(r.Next(0, 256), r.Next(0, 256), r.Next(0, 256)); + Color cl = new Color(); ColorDialog dialog = new(); - if (dialog.ShowDialog() == DialogResult.OK) - { cl = dialog.Color; } + 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; } @@ -84,7 +84,7 @@ public partial class ServiceForm2 : Form // Удаление объекта private void btnRemoveCar_Click(object sender, EventArgs e) { - if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) + if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null) return; if (MessageBox.Show("[*] Remove object: Are you sure?", "Remove", @@ -135,4 +135,6 @@ public partial class ServiceForm2 : Form } pictureBox.Image = _company.Show(); } + + // continue } -- 2.25.1 From 0498d0da74fadd6ca3e48800dd2c87c8860f76ed Mon Sep 17 00:00:00 2001 From: DelphyAlmond Date: Sat, 15 Jun 2024 09:05:36 +0400 Subject: [PATCH 07/13] collections --- .../AbstractCompany.cs | 10 +- .../{ => CollectionGenericObj}/ArrayGenObj.cs | 6 +- .../CollectionGenericObj/CollectionType.cs | 8 + .../ICollectionGenObj.cs | 2 +- .../{ => CollectionGenericObj}/ListGenObj.cs | 18 +- .../ShipSharingService.cs | 2 +- .../CollectionGenericObj/StorageCollection.cs | 57 +++++ ProjectCruiser/MoveStrategy/MoveToBorder.cs | 8 +- ProjectCruiser/ServiceForm2.Designer.cs | 198 +++++++++--------- ProjectCruiser/ServiceForm2.cs | 98 ++++++++- 10 files changed, 280 insertions(+), 127 deletions(-) rename ProjectCruiser/{ => CollectionGenericObj}/AbstractCompany.cs (87%) rename ProjectCruiser/{ => CollectionGenericObj}/ArrayGenObj.cs (94%) create mode 100644 ProjectCruiser/CollectionGenericObj/CollectionType.cs rename ProjectCruiser/{ => CollectionGenericObj}/ICollectionGenObj.cs (94%) rename ProjectCruiser/{ => CollectionGenericObj}/ListGenObj.cs (74%) rename ProjectCruiser/{ => CollectionGenericObj}/ShipSharingService.cs (97%) create mode 100644 ProjectCruiser/CollectionGenericObj/StorageCollection.cs diff --git a/ProjectCruiser/AbstractCompany.cs b/ProjectCruiser/CollectionGenericObj/AbstractCompany.cs similarity index 87% rename from ProjectCruiser/AbstractCompany.cs rename to ProjectCruiser/CollectionGenericObj/AbstractCompany.cs index e9b42e3..d94f1c8 100644 --- a/ProjectCruiser/AbstractCompany.cs +++ b/ProjectCruiser/CollectionGenericObj/AbstractCompany.cs @@ -1,5 +1,5 @@ using ProjectCruiser.DrawningSamples; -namespace ProjectCruiser; +namespace ProjectCruiser.CollectionGenericObj; /// Абстракция компании, хранящий коллекцию автомобилей /// @@ -31,12 +31,12 @@ public abstract class AbstractCompany // Перегрузка оператора сложения для класса // [ ! ] insted of bool: - public static int operator +(AbstractCompany cmp, - DrawningBase trasport) => (cmp._collection.Insert(trasport)); + public static int operator +(AbstractCompany company, + DrawningBase trasport) => company._collection.Insert(trasport); // Перегрузка оператора удаления для класса - public static DrawningBase operator -(AbstractCompany cmp, - int pos) => (cmp._collection.Remove(pos)); + public static DrawningBase operator -(AbstractCompany company, + int pos) => company._collection.Remove(pos); // Получение случайного объекта из коллекции public DrawningBase? GetRandomObject() diff --git a/ProjectCruiser/ArrayGenObj.cs b/ProjectCruiser/CollectionGenericObj/ArrayGenObj.cs similarity index 94% rename from ProjectCruiser/ArrayGenObj.cs rename to ProjectCruiser/CollectionGenericObj/ArrayGenObj.cs index a20cf25..620dcc8 100644 --- a/ProjectCruiser/ArrayGenObj.cs +++ b/ProjectCruiser/CollectionGenericObj/ArrayGenObj.cs @@ -1,4 +1,4 @@ -namespace ProjectCruiser; +namespace ProjectCruiser.CollectionGenericObj; public class ArrayGenObj : ICollectionGenObj where T : class @@ -8,7 +8,7 @@ public class ArrayGenObj : ICollectionGenObj public int Count => _collection.Length; public int SetMaxCount { - set + set { if (value > 0) { @@ -64,7 +64,7 @@ public class ArrayGenObj : ICollectionGenObj for (int i = 0; i < Count; i++) { - if (_collection[i] == null + if (_collection[i] == null && min_diff > Math.Abs(index - i)) { min_diff = Math.Abs(index - i); diff --git a/ProjectCruiser/CollectionGenericObj/CollectionType.cs b/ProjectCruiser/CollectionGenericObj/CollectionType.cs new file mode 100644 index 0000000..95dc249 --- /dev/null +++ b/ProjectCruiser/CollectionGenericObj/CollectionType.cs @@ -0,0 +1,8 @@ +namespace ProjectCruiser.CollectionGenericObj; + +public enum CollectionType +{ + None = 0, + Array = 1, + List = 2 +} diff --git a/ProjectCruiser/ICollectionGenObj.cs b/ProjectCruiser/CollectionGenericObj/ICollectionGenObj.cs similarity index 94% rename from ProjectCruiser/ICollectionGenObj.cs rename to ProjectCruiser/CollectionGenericObj/ICollectionGenObj.cs index 9012d74..d87998c 100644 --- a/ProjectCruiser/ICollectionGenObj.cs +++ b/ProjectCruiser/CollectionGenericObj/ICollectionGenObj.cs @@ -1,4 +1,4 @@ -namespace ProjectCruiser; +namespace ProjectCruiser.CollectionGenericObj; public interface ICollectionGenObj where T : class { diff --git a/ProjectCruiser/ListGenObj.cs b/ProjectCruiser/CollectionGenericObj/ListGenObj.cs similarity index 74% rename from ProjectCruiser/ListGenObj.cs rename to ProjectCruiser/CollectionGenericObj/ListGenObj.cs index c945997..0b33867 100644 --- a/ProjectCruiser/ListGenObj.cs +++ b/ProjectCruiser/CollectionGenericObj/ListGenObj.cs @@ -1,10 +1,10 @@ using System; using System.Reflection; -namespace ProjectCruiser; +namespace ProjectCruiser.CollectionGenericObj; // Параметризованный набор объектов -public class ListGenericObjects : ICollectionGenObj +public class ListGenObj : ICollectionGenObj where T : class { // Список объектов, которые храним @@ -16,14 +16,14 @@ public class ListGenericObjects : ICollectionGenObj public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } - public ListGenericObjects() + public ListGenObj() { _collection = new(); } public T? GetItem(int position) { - if (position > _maxCount - 1 || position < 0) + if (position >= Count || position < 0) { return null; } @@ -33,18 +33,20 @@ public class ListGenericObjects : ICollectionGenObj public int Insert(T obj) { - if (Count + 1 < _maxCount || obj == null) + if (Count >= _maxCount || obj == null) { return -1; } + _collection.Add(obj); return Count; } public int Insert(T obj, int position) { - if (position >= _maxCount || position < 0 || - _collection[position] != null) + if (position >= _maxCount || Count >= _maxCount || + position < 0 || _collection[position] != null + || obj == null) { return -1; } @@ -56,7 +58,7 @@ public class ListGenericObjects : ICollectionGenObj public T? Remove(int position) { if (position >= Count || position < 0) - // on the other positions items don't exist + // on the other positions items don't exist { return null; } diff --git a/ProjectCruiser/ShipSharingService.cs b/ProjectCruiser/CollectionGenericObj/ShipSharingService.cs similarity index 97% rename from ProjectCruiser/ShipSharingService.cs rename to ProjectCruiser/CollectionGenericObj/ShipSharingService.cs index e0098d4..e430deb 100644 --- a/ProjectCruiser/ShipSharingService.cs +++ b/ProjectCruiser/CollectionGenericObj/ShipSharingService.cs @@ -1,5 +1,5 @@ using ProjectCruiser.DrawningSamples; -namespace ProjectCruiser; +namespace ProjectCruiser.CollectionGenericObj; public class ShipSharingService : AbstractCompany { diff --git a/ProjectCruiser/CollectionGenericObj/StorageCollection.cs b/ProjectCruiser/CollectionGenericObj/StorageCollection.cs new file mode 100644 index 0000000..f835efa --- /dev/null +++ b/ProjectCruiser/CollectionGenericObj/StorageCollection.cs @@ -0,0 +1,57 @@ +namespace ProjectCruiser.CollectionGenericObj; + +public class StorageCollection +where T : class +{ + // Словарь (хранилище) с коллекциями < name, type (class) > + readonly Dictionary> _storages; + + // Возвращение списка названий коллекций + public List Keys => _storages.Keys.ToList(); + + public StorageCollection() + { + _storages = new Dictionary>(); + } + + /// Добавление коллекции в хранилище + /// Название коллекции + /// тип коллекции + public void AddCollection(string name, CollectionType collType) + { + if (name == null || _storages.ContainsKey(name) + || collType == CollectionType.None) + { + return; + } + + switch (collType) + { + case CollectionType.List: _storages.Add(name, new ListGenObj()); break; + // _storages[name] = new ListGenericObjects(); break; [*] + + case CollectionType.Array: _storages.Add(name, new ArrayGenObj()); break; + } + } + + /// Удаление коллекции ( по ключу-строке - её имени ) + /// Название коллекции + public void DelCollection(string name) + { + if (_storages.ContainsKey(name)) _storages.Remove(name); + return; + } + + /// Доступ к коллекции ( по ключу-строке - её имени ) + public ICollectionGenObj? this[string name] + { + get => _storages.ContainsKey(name) ? _storages[name] : null; + /* ^^^ + { + if (_storages.ContainsKey(name)) return _storages[name]; + return null; + } + */ + } +} + diff --git a/ProjectCruiser/MoveStrategy/MoveToBorder.cs b/ProjectCruiser/MoveStrategy/MoveToBorder.cs index 22137e2..85bc0d0 100644 --- a/ProjectCruiser/MoveStrategy/MoveToBorder.cs +++ b/ProjectCruiser/MoveStrategy/MoveToBorder.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace ProjectCruiser.MoveStrategy; +namespace ProjectCruiser.MoveStrategy; public class MoveToBorder : AbstractStrategy { diff --git a/ProjectCruiser/ServiceForm2.Designer.cs b/ProjectCruiser/ServiceForm2.Designer.cs index a9db303..ed3cc6a 100644 --- a/ProjectCruiser/ServiceForm2.Designer.cs +++ b/ProjectCruiser/ServiceForm2.Designer.cs @@ -31,26 +31,26 @@ comboBoxArrList = new ComboBox(); btnAddBase = new Button(); groupBox = new GroupBox(); + toolPanel = new Panel(); btnUpdate = new Button(); btnTest = new Button(); - btnDelete = new Button(); maskedTextBoxPosition = new MaskedTextBox(); + btnDelete = new Button(); btnAddCruiser = new Button(); + btnCreateCompany = new Button(); pictureBox = new PictureBox(); companyPanel = new Panel(); - label = new Label(); - maskedTxtBoxCName = new MaskedTextBox(); - rBtnArray = new RadioButton(); - rBtnList = new RadioButton(); - btnAddCollection = new Button(); - listBox = new ListBox(); btnDeleteCollection = new Button(); - btnCreateCompany = new Button(); - toolPanel = new Panel(); + listBox = new ListBox(); + btnAddCollection = new Button(); + rBtnList = new RadioButton(); + rBtnArray = new RadioButton(); + maskedTxtBoxCName = new MaskedTextBox(); + label = new Label(); groupBox.SuspendLayout(); + toolPanel.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); companyPanel.SuspendLayout(); - toolPanel.SuspendLayout(); SuspendLayout(); // // comboBoxArrList @@ -60,7 +60,7 @@ comboBoxArrList.Items.AddRange(new object[] { "Storage" }); comboBoxArrList.Location = new Point(17, 41); comboBoxArrList.Name = "comboBoxArrList"; - comboBoxArrList.Size = new Size(243, 40); + comboBoxArrList.Size = new Size(241, 40); comboBoxArrList.TabIndex = 0; comboBoxArrList.SelectedIndexChanged += SelectorCompany_SelectedIndexChanged; // @@ -78,16 +78,31 @@ // groupBox // groupBox.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + groupBox.Controls.Add(companyPanel); groupBox.Controls.Add(toolPanel); groupBox.Controls.Add(btnCreateCompany); groupBox.Controls.Add(comboBoxArrList); - groupBox.Location = new Point(1402, 12); + groupBox.Location = new Point(1421, 10); groupBox.Name = "groupBox"; - groupBox.Size = new Size(275, 986); + groupBox.Size = new Size(273, 986); groupBox.TabIndex = 2; groupBox.TabStop = false; groupBox.Text = "Tool panel"; // + // toolPanel + // + toolPanel.Controls.Add(btnUpdate); + toolPanel.Controls.Add(btnTest); + toolPanel.Controls.Add(maskedTextBoxPosition); + toolPanel.Controls.Add(btnDelete); + toolPanel.Controls.Add(btnAddCruiser); + toolPanel.Controls.Add(btnAddBase); + toolPanel.Enabled = false; + toolPanel.Location = new Point(26, 593); + toolPanel.Name = "toolPanel"; + toolPanel.Size = new Size(226, 377); + toolPanel.TabIndex = 13; + // // btnUpdate // btnUpdate.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; @@ -110,6 +125,16 @@ btnTest.UseVisualStyleBackColor = true; btnTest.Click += btnChooseforTest_Click; // + // maskedTextBoxPosition + // + maskedTextBoxPosition.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + maskedTextBoxPosition.Location = new Point(17, 119); + maskedTextBoxPosition.Mask = "00"; + maskedTextBoxPosition.Name = "maskedTextBoxPosition"; + maskedTextBoxPosition.Size = new Size(192, 39); + maskedTextBoxPosition.TabIndex = 3; + maskedTextBoxPosition.ValidatingType = typeof(int); + // // btnDelete // btnDelete.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; @@ -121,16 +146,6 @@ btnDelete.UseVisualStyleBackColor = true; btnDelete.Click += btnRemoveCar_Click; // - // maskedTextBoxPosition - // - maskedTextBoxPosition.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - maskedTextBoxPosition.Location = new Point(17, 119); - maskedTextBoxPosition.Mask = "00"; - maskedTextBoxPosition.Name = "maskedTextBoxPosition"; - maskedTextBoxPosition.Size = new Size(192, 39); - maskedTextBoxPosition.TabIndex = 3; - maskedTextBoxPosition.ValidatingType = typeof(int); - // // btnAddCruiser // btnAddCruiser.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; @@ -142,12 +157,23 @@ btnAddCruiser.UseVisualStyleBackColor = true; btnAddCruiser.Click += btnAddAdvanced_Click; // + // btnCreateCompany + // + btnCreateCompany.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + btnCreateCompany.Location = new Point(17, 526); + btnCreateCompany.Name = "btnCreateCompany"; + btnCreateCompany.Size = new Size(243, 61); + btnCreateCompany.TabIndex = 12; + btnCreateCompany.Text = "Create Company"; + btnCreateCompany.UseVisualStyleBackColor = true; + btnCreateCompany.Click += btnCreateCompany_Click; + // // pictureBox // pictureBox.Dock = DockStyle.Left; pictureBox.Location = new Point(0, 0); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(1385, 1007); + pictureBox.Size = new Size(1415, 1007); pictureBox.TabIndex = 3; pictureBox.TabStop = false; // @@ -160,38 +186,40 @@ companyPanel.Controls.Add(rBtnArray); companyPanel.Controls.Add(maskedTxtBoxCName); companyPanel.Controls.Add(label); - companyPanel.Location = new Point(1419, 101); - companyPanel.Name = "panel1"; + companyPanel.Location = new Point(17, 91); + companyPanel.Name = "companyPanel"; companyPanel.Size = new Size(243, 429); companyPanel.TabIndex = 7; // - // label + // btnDeleteCollection // - label.AutoSize = true; - label.Location = new Point(29, 6); - label.Name = "label"; - label.Size = new Size(188, 32); - label.TabIndex = 0; - label.Text = "Collection name"; + btnDeleteCollection.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + btnDeleteCollection.Location = new Point(15, 371); + btnDeleteCollection.Name = "btnDeleteCollection"; + btnDeleteCollection.Size = new Size(214, 43); + btnDeleteCollection.TabIndex = 11; + btnDeleteCollection.Text = "Remove Collection"; + btnDeleteCollection.UseVisualStyleBackColor = true; + btnDeleteCollection.Click += btnCollectionDel_Click; // - // maskedTxtBoxCName + // listBox // - maskedTxtBoxCName.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - maskedTxtBoxCName.Location = new Point(16, 43); - maskedTxtBoxCName.Name = "maskedTextBox1"; - maskedTxtBoxCName.Size = new Size(214, 39); - maskedTxtBoxCName.TabIndex = 7; + listBox.FormattingEnabled = true; + listBox.Location = new Point(16, 199); + listBox.Name = "listBox"; + listBox.Size = new Size(214, 164); + listBox.TabIndex = 10; // - // rBtnArray + // btnAddCollection // - rBtnArray.AutoSize = true; - rBtnArray.Location = new Point(16, 88); - rBtnArray.Name = "rBtnArray"; - rBtnArray.Size = new Size(100, 36); - rBtnArray.TabIndex = 8; - rBtnArray.TabStop = true; - rBtnArray.Text = "Array"; - rBtnArray.UseVisualStyleBackColor = true; + btnAddCollection.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + btnAddCollection.Location = new Point(15, 130); + btnAddCollection.Name = "btnAddCollection"; + btnAddCollection.Size = new Size(214, 61); + btnAddCollection.TabIndex = 7; + btnAddCollection.Text = "Add Collection"; + btnAddCollection.UseVisualStyleBackColor = true; + btnAddCollection.Click += btnCollectionAdd_Click; // // rBtnList // @@ -204,73 +232,49 @@ rBtnList.Text = "List"; rBtnList.UseVisualStyleBackColor = true; // - // btnAddCollection + // rBtnArray // - btnAddCollection.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - btnAddCollection.Location = new Point(15, 130); - btnAddCollection.Name = "btnAddCollection"; - btnAddCollection.Size = new Size(214, 61); - btnAddCollection.TabIndex = 7; - btnAddCollection.Text = "Add Collection"; - btnAddCollection.UseVisualStyleBackColor = true; + rBtnArray.AutoSize = true; + rBtnArray.Location = new Point(16, 88); + rBtnArray.Name = "rBtnArray"; + rBtnArray.Size = new Size(100, 36); + rBtnArray.TabIndex = 8; + rBtnArray.TabStop = true; + rBtnArray.Text = "Array"; + rBtnArray.UseVisualStyleBackColor = true; // - // listBox1 + // maskedTxtBoxCName // - listBox.FormattingEnabled = true; - listBox.Location = new Point(16, 199); - listBox.Name = "listBox1"; - listBox.Size = new Size(214, 164); - listBox.TabIndex = 10; + maskedTxtBoxCName.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + maskedTxtBoxCName.Location = new Point(16, 43); + maskedTxtBoxCName.Name = "maskedTxtBoxCName"; + maskedTxtBoxCName.Size = new Size(214, 39); + maskedTxtBoxCName.TabIndex = 7; // - // btnDeleteCollection + // label // - btnDeleteCollection.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - btnDeleteCollection.Location = new Point(15, 371); - btnDeleteCollection.Name = "btnDeleteCollection"; - btnDeleteCollection.Size = new Size(214, 43); - btnDeleteCollection.TabIndex = 11; - btnDeleteCollection.Text = "Remove Collection"; - btnDeleteCollection.UseVisualStyleBackColor = true; - // - // btnCreateCompany - // - btnCreateCompany.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - btnCreateCompany.Location = new Point(17, 526); - btnCreateCompany.Name = "btnCreateCompany"; - btnCreateCompany.Size = new Size(243, 61); - btnCreateCompany.TabIndex = 12; - btnCreateCompany.Text = "Create Company"; - btnCreateCompany.UseVisualStyleBackColor = true; - // - // toolPanel - // - toolPanel.Controls.Add(btnUpdate); - toolPanel.Controls.Add(btnTest); - toolPanel.Controls.Add(maskedTextBoxPosition); - toolPanel.Controls.Add(btnDelete); - toolPanel.Controls.Add(btnAddCruiser); - toolPanel.Controls.Add(btnAddBase); - toolPanel.Location = new Point(26, 596); - toolPanel.Name = "panel2"; - toolPanel.Size = new Size(226, 377); - toolPanel.TabIndex = 13; + label.AutoSize = true; + label.Location = new Point(29, 6); + label.Name = "label"; + label.Size = new Size(188, 32); + label.TabIndex = 0; + label.Text = "Collection name"; // // ServiceForm2 // AutoScaleDimensions = new SizeF(13F, 32F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1689, 1007); - Controls.Add(companyPanel); + ClientSize = new Size(1700, 1007); Controls.Add(pictureBox); Controls.Add(groupBox); Name = "ServiceForm2"; Text = "ServiceForm2"; groupBox.ResumeLayout(false); + toolPanel.ResumeLayout(false); + toolPanel.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); companyPanel.ResumeLayout(false); companyPanel.PerformLayout(); - toolPanel.ResumeLayout(false); - toolPanel.PerformLayout(); ResumeLayout(false); } diff --git a/ProjectCruiser/ServiceForm2.cs b/ProjectCruiser/ServiceForm2.cs index 80ae0ad..02bbd58 100644 --- a/ProjectCruiser/ServiceForm2.cs +++ b/ProjectCruiser/ServiceForm2.cs @@ -1,20 +1,28 @@ -using System.Windows.Forms; +using System.Collections.Generic; +using System.Windows.Forms; +using System.Xml.Linq; +using ProjectCruiser.CollectionGenericObj; using ProjectCruiser.DrawningSamples; +using static System.Windows.Forms.VisualStyles.VisualStyleElement; namespace ProjectCruiser; public partial class ServiceForm2 : Form { // Компания - private AbstractCompany? _company; + private AbstractCompany? _company = null; + + private readonly StorageCollection _storageCollection; + public ServiceForm2() { InitializeComponent(); - _company = null; + _storageCollection = new(); } // Выбор компании private void SelectorCompany_SelectedIndexChanged(object sender, EventArgs e) { + /* switch (comboBoxArrList.Text) { case "Storage": @@ -22,6 +30,9 @@ public partial class ServiceForm2 : Form new ArrayGenObj()); break; } + */ + + toolPanel.Enabled = false; } // Color picker (default : random) @@ -62,7 +73,6 @@ public partial class ServiceForm2 : Form break; case nameof(DrawningCruiser): - // (TODO) вызов диалогового окна для выбора цвета >>> drawningCar = new DrawningCruiser(random.Next(100, 300), random.Next(1000, 3000), pickColor(random), pickColor(random), Convert.ToBoolean(random.Next(0, 2))); @@ -136,5 +146,83 @@ public partial class ServiceForm2 : Form pictureBox.Image = _company.Show(); } - // continue + private void btnCollectionAdd_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(maskedTxtBoxCName.Text) || (!rBtnList.Checked && !rBtnArray.Checked)) + { + MessageBox.Show("Enter correct data or choose an option", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + + CollectionType collType = CollectionType.None; + + if (rBtnArray.Checked) + { + collType = CollectionType.Array; + } + else if (rBtnList.Checked) + { + collType = CollectionType.List; + } + + _storageCollection.AddCollection(maskedTxtBoxCName.Text, collType); + RefreshListBoxItems(); + } + + private void btnCollectionDel_Click(object sender, EventArgs e) + { + if (listBox.SelectedItem == null || listBox.SelectedIndex < 0) + { + MessageBox.Show("Collection was not choosed"); + return; + } + if (MessageBox.Show("Are you sure?", "Removing", MessageBoxButtons.OK, MessageBoxIcon.Question) != DialogResult.OK) + { + return; + } + _storageCollection.DelCollection(listBox.SelectedItem.ToString()); + RefreshListBoxItems(); + } + + private void RefreshListBoxItems() + { + listBox.Items.Clear(); + for (int i = 0; i < _storageCollection.Keys?.Count; ++i) + { + string? collName = _storageCollection.Keys?[i]; + if (!string.IsNullOrEmpty(collName)) + { + listBox.Items.Add(collName); + } + } + } + + private void btnCreateCompany_Click(object sender, EventArgs e) + { + if (listBox.SelectedIndex < 0 || listBox.SelectedItem == null) + { + MessageBox.Show("Collection wasn't choosed"); + return; + } + + ICollectionGenObj? collection = + _storageCollection[listBox.SelectedItem.ToString() ?? string.Empty]; + + if (collection == null) + { + MessageBox.Show("Collection wasn't initialized"); + return; + } + + switch (comboBoxArrList.Text) + { + case "Storage": + _company = new ShipSharingService(pictureBox.Width, + pictureBox.Height, collection); + break; + } + + toolPanel.Enabled = true; // block of buttons at the right bottom + RefreshListBoxItems(); + } } -- 2.25.1 From f52c0fc2ca3493b7d5281cb3d216f1b4b5ce6385 Mon Sep 17 00:00:00 2001 From: DelphyAlmond Date: Sat, 15 Jun 2024 09:53:32 +0400 Subject: [PATCH 08/13] In process : make helicopter non-default --- .../CollectionGenericObj/StorageCollection.cs | 6 - ProjectCruiser/EditorForm3.Designer.cs | 344 ++++++++++++++++++ ProjectCruiser/EditorForm3.cs | 124 +++++++ ProjectCruiser/EditorForm3.resx | 120 ++++++ ProjectCruiser/Entities/EntityBase.cs | 5 + ProjectCruiser/Entities/EntityCruiser.cs | 5 + ProjectCruiser/ServiceForm2.Designer.cs | 232 ++++++------ ProjectCruiser/ServiceForm2.cs | 55 +-- ProjectCruiser/ShipDelegate.cs | 6 + 9 files changed, 725 insertions(+), 172 deletions(-) create mode 100644 ProjectCruiser/EditorForm3.Designer.cs create mode 100644 ProjectCruiser/EditorForm3.cs create mode 100644 ProjectCruiser/EditorForm3.resx create mode 100644 ProjectCruiser/ShipDelegate.cs diff --git a/ProjectCruiser/CollectionGenericObj/StorageCollection.cs b/ProjectCruiser/CollectionGenericObj/StorageCollection.cs index f835efa..cd62ac5 100644 --- a/ProjectCruiser/CollectionGenericObj/StorageCollection.cs +++ b/ProjectCruiser/CollectionGenericObj/StorageCollection.cs @@ -46,12 +46,6 @@ where T : class public ICollectionGenObj? this[string name] { get => _storages.ContainsKey(name) ? _storages[name] : null; - /* ^^^ - { - if (_storages.ContainsKey(name)) return _storages[name]; - return null; - } - */ } } diff --git a/ProjectCruiser/EditorForm3.Designer.cs b/ProjectCruiser/EditorForm3.Designer.cs new file mode 100644 index 0000000..ae42415 --- /dev/null +++ b/ProjectCruiser/EditorForm3.Designer.cs @@ -0,0 +1,344 @@ +namespace ProjectCruiser +{ + partial class EditorForm3 + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + ParametersBox = new GroupBox(); + AdvLabel = new Label(); + BaseLabel = new Label(); + groupBox2 = new GroupBox(); + PurpleP = new Panel(); + GreenP = new Panel(); + PinkP = new Panel(); + OrangeP = new Panel(); + CyanP = new Panel(); + YellowP = new Panel(); + RedP = new Panel(); + BlueP = new Panel(); + checkBoxPads = new CheckBox(); + checkBoxHangars = new CheckBox(); + WeightN = new NumericUpDown(); + SpeedN = new NumericUpDown(); + Label = new Label(); + Showcase = new PictureBox(); + btnAdd = new Button(); + btnCancel = new Button(); + panelObject = new Panel(); + labelAcolor = new Label(); + labelMcolor = new Label(); + ParametersBox.SuspendLayout(); + groupBox2.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)WeightN).BeginInit(); + ((System.ComponentModel.ISupportInitialize)SpeedN).BeginInit(); + ((System.ComponentModel.ISupportInitialize)Showcase).BeginInit(); + panelObject.SuspendLayout(); + SuspendLayout(); + // + // ParametersBox + // + ParametersBox.Controls.Add(AdvLabel); + ParametersBox.Controls.Add(BaseLabel); + ParametersBox.Controls.Add(groupBox2); + ParametersBox.Controls.Add(checkBoxPads); + ParametersBox.Controls.Add(checkBoxHangars); + ParametersBox.Controls.Add(WeightN); + ParametersBox.Controls.Add(SpeedN); + ParametersBox.Controls.Add(Label); + ParametersBox.Location = new Point(12, 0); + ParametersBox.Name = "ParametersBox"; + ParametersBox.Size = new Size(388, 495); + ParametersBox.TabIndex = 0; + ParametersBox.TabStop = false; + ParametersBox.Text = "Parameters"; + // + // AdvLabel + // + AdvLabel.BorderStyle = BorderStyle.FixedSingle; + AdvLabel.Location = new Point(175, 428); + AdvLabel.Name = "AdvLabel"; + AdvLabel.Size = new Size(184, 46); + AdvLabel.TabIndex = 5; + AdvLabel.Text = "Advanced"; + AdvLabel.TextAlign = ContentAlignment.MiddleCenter; + AdvLabel.MouseDown += BaseAdvLabel_MouseDown; + // + // BaseLabel + // + BaseLabel.BorderStyle = BorderStyle.FixedSingle; + BaseLabel.Location = new Point(17, 428); + BaseLabel.Name = "BaseLabel"; + BaseLabel.Size = new Size(132, 46); + BaseLabel.TabIndex = 4; + BaseLabel.Text = "Base"; + BaseLabel.TextAlign = ContentAlignment.MiddleCenter; + BaseLabel.MouseDown += BaseAdvLabel_MouseDown; + // + // groupBox2 + // + groupBox2.Controls.Add(PurpleP); + groupBox2.Controls.Add(GreenP); + groupBox2.Controls.Add(PinkP); + groupBox2.Controls.Add(OrangeP); + groupBox2.Controls.Add(CyanP); + groupBox2.Controls.Add(YellowP); + groupBox2.Controls.Add(RedP); + groupBox2.Controls.Add(BlueP); + groupBox2.Location = new Point(17, 197); + groupBox2.Name = "groupBox2"; + groupBox2.Size = new Size(342, 213); + groupBox2.TabIndex = 1; + groupBox2.TabStop = false; + groupBox2.Text = "Color picker"; + // + // PurpleP + // + PurpleP.BackColor = Color.DarkViolet; + PurpleP.Location = new Point(260, 126); + PurpleP.Name = "PurpleP"; + PurpleP.Size = new Size(63, 59); + PurpleP.TabIndex = 12; + // + // GreenP + // + GreenP.BackColor = Color.SpringGreen; + GreenP.Location = new Point(259, 49); + GreenP.Name = "GreenP"; + GreenP.Size = new Size(63, 59); + GreenP.TabIndex = 9; + // + // PinkP + // + PinkP.BackColor = Color.DeepPink; + PinkP.Location = new Point(180, 126); + PinkP.Name = "PinkP"; + PinkP.Size = new Size(63, 59); + PinkP.TabIndex = 11; + // + // OrangeP + // + OrangeP.BackColor = Color.DarkOrange; + OrangeP.Location = new Point(180, 49); + OrangeP.Name = "OrangeP"; + OrangeP.Size = new Size(63, 59); + OrangeP.TabIndex = 8; + // + // CyanP + // + CyanP.BackColor = Color.Cyan; + CyanP.Location = new Point(100, 126); + CyanP.Name = "CyanP"; + CyanP.Size = new Size(63, 59); + CyanP.TabIndex = 10; + // + // YellowP + // + YellowP.BackColor = Color.Gold; + YellowP.Location = new Point(19, 126); + YellowP.Name = "YellowP"; + YellowP.Size = new Size(63, 59); + YellowP.TabIndex = 9; + // + // RedP + // + RedP.BackColor = Color.Firebrick; + RedP.Location = new Point(100, 49); + RedP.Name = "RedP"; + RedP.Size = new Size(63, 59); + RedP.TabIndex = 7; + // + // BlueP + // + BlueP.BackColor = SystemColors.Highlight; + BlueP.Location = new Point(19, 49); + BlueP.Name = "BlueP"; + BlueP.Size = new Size(63, 59); + BlueP.TabIndex = 6; + // + // checkBoxPads + // + checkBoxPads.AutoSize = true; + checkBoxPads.Location = new Point(24, 142); + checkBoxPads.Name = "checkBoxPads"; + checkBoxPads.Size = new Size(203, 36); + checkBoxPads.TabIndex = 3; + checkBoxPads.Text = "Helicopter pad"; + checkBoxPads.UseVisualStyleBackColor = true; + // + // checkBoxHangars + // + checkBoxHangars.AutoSize = true; + checkBoxHangars.Location = new Point(234, 142); + checkBoxHangars.Name = "checkBoxHangars"; + checkBoxHangars.Size = new Size(133, 36); + checkBoxHangars.TabIndex = 1; + checkBoxHangars.Text = "Hangars"; + checkBoxHangars.UseVisualStyleBackColor = true; + // + // WeightN + // + WeightN.Location = new Point(198, 88); + WeightN.Maximum = new decimal(new int[] { 1000, 0, 0, 0 }); + WeightN.Minimum = new decimal(new int[] { 100, 0, 0, 0 }); + WeightN.Name = "WeightN"; + WeightN.Size = new Size(142, 39); + WeightN.TabIndex = 2; + WeightN.Value = new decimal(new int[] { 100, 0, 0, 0 }); + // + // SpeedN + // + SpeedN.Location = new Point(36, 88); + SpeedN.Maximum = new decimal(new int[] { 1000, 0, 0, 0 }); + SpeedN.Minimum = new decimal(new int[] { 100, 0, 0, 0 }); + SpeedN.Name = "SpeedN"; + SpeedN.Size = new Size(142, 39); + SpeedN.TabIndex = 1; + SpeedN.Value = new decimal(new int[] { 100, 0, 0, 0 }); + // + // Label + // + Label.AutoSize = true; + Label.Location = new Point(36, 53); + Label.Name = "Label"; + Label.Size = new Size(304, 32); + Label.TabIndex = 1; + Label.Text = "Speed Weight"; + // + // Showcase + // + Showcase.Location = new Point(58, 98); + Showcase.Name = "Showcase"; + Showcase.Size = new Size(458, 272); + Showcase.TabIndex = 1; + Showcase.TabStop = false; + // + // btnAdd + // + btnAdd.Location = new Point(419, 447); + btnAdd.Name = "btnAdd"; + btnAdd.Size = new Size(268, 46); + btnAdd.TabIndex = 2; + btnAdd.Text = "Add"; + btnAdd.UseVisualStyleBackColor = true; + btnAdd.Click += AddButton_Click; + // + // btnCancel + // + btnCancel.Location = new Point(694, 447); + btnCancel.Name = "btnCancel"; + btnCancel.Size = new Size(286, 46); + btnCancel.TabIndex = 3; + btnCancel.Text = "Cancel"; + btnCancel.UseVisualStyleBackColor = true; + // + // panelObject + // + panelObject.AllowDrop = true; + panelObject.Controls.Add(labelAcolor); + panelObject.Controls.Add(labelMcolor); + panelObject.Controls.Add(Showcase); + panelObject.Location = new Point(419, 12); + panelObject.Name = "panelObject"; + panelObject.Size = new Size(561, 410); + panelObject.TabIndex = 4; + panelObject.DragDrop += PanelObject_DragDrop; + panelObject.DragEnter += PanelObject_DragEnter; + // + // labelAcolor + // + labelAcolor.AllowDrop = true; + labelAcolor.BorderStyle = BorderStyle.FixedSingle; + labelAcolor.Location = new Point(253, 39); + labelAcolor.Name = "labelAcolor"; + labelAcolor.Size = new Size(263, 42); + labelAcolor.TabIndex = 7; + labelAcolor.Text = "Additional color"; + labelAcolor.TextAlign = ContentAlignment.MiddleCenter; + labelAcolor.DragDrop += AdditionalColor_DragDrop; + labelAcolor.DragEnter += AdditionalColor_DragEnter; + // + // labelMcolor + // + labelMcolor.AllowDrop = true; + labelMcolor.BorderStyle = BorderStyle.FixedSingle; + labelMcolor.Location = new Point(58, 39); + labelMcolor.Name = "labelMcolor"; + labelMcolor.Size = new Size(180, 42); + labelMcolor.TabIndex = 6; + labelMcolor.Text = "Main color"; + labelMcolor.TextAlign = ContentAlignment.MiddleCenter; + labelMcolor.DragDrop += BodyColor_DragDrop; + labelMcolor.DragEnter += BodyColor_DragEnter; + // + // EditorForm3 + // + AutoScaleDimensions = new SizeF(13F, 32F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(992, 516); + Controls.Add(panelObject); + Controls.Add(btnCancel); + Controls.Add(btnAdd); + Controls.Add(ParametersBox); + Name = "EditorForm3"; + Text = "FormTransportConfig"; + ParametersBox.ResumeLayout(false); + ParametersBox.PerformLayout(); + groupBox2.ResumeLayout(false); + ((System.ComponentModel.ISupportInitialize)WeightN).EndInit(); + ((System.ComponentModel.ISupportInitialize)SpeedN).EndInit(); + ((System.ComponentModel.ISupportInitialize)Showcase).EndInit(); + panelObject.ResumeLayout(false); + ResumeLayout(false); + } + + #endregion + + private GroupBox ParametersBox; + private Label Label; + private CheckBox checkBoxPads; + private CheckBox checkBoxHangars; + private NumericUpDown WeightN; + private NumericUpDown SpeedN; + private GroupBox groupBox2; + private Label BaseLabel; + private Label AdvLabel; + private Panel PurpleP; + private Panel GreenP; + private Panel PinkP; + private Panel OrangeP; + private Panel CyanP; + private Panel YellowP; + private Panel RedP; + private Panel BlueP; + private PictureBox Showcase; + private Button btnAdd; + private Button btnCancel; + private Panel panelObject; + private Label labelMcolor; + private Label labelAcolor; + } +} \ No newline at end of file diff --git a/ProjectCruiser/EditorForm3.cs b/ProjectCruiser/EditorForm3.cs new file mode 100644 index 0000000..949cbf5 --- /dev/null +++ b/ProjectCruiser/EditorForm3.cs @@ -0,0 +1,124 @@ +using ProjectCruiser.DrawningSamples; +using ProjectCruiser.Entities; +using System; + +namespace ProjectCruiser; +public partial class EditorForm3 : Form +{ + private DrawningBase _cruiser; + + // private event Action? shipDelegate; + private event ShipDelegate? shipDelegate; + + public EditorForm3() + { + InitializeComponent(); + BlueP.MouseDown += Panel_MouseDown; + RedP.MouseDown += Panel_MouseDown; + PinkP.MouseDown += Panel_MouseDown; + YellowP.MouseDown += Panel_MouseDown; + CyanP.MouseDown += Panel_MouseDown; + PurpleP.MouseDown += Panel_MouseDown; + GreenP.MouseDown += Panel_MouseDown; + OrangeP.MouseDown += Panel_MouseDown; + btnCancel.Click += (sender, e) => Close(); + } + + public void AddEvent(ShipDelegate del)// Action delegator) + { + if (shipDelegate == null) shipDelegate = del; + else shipDelegate += del; + //shipDelegate += del; + } + + private void DrawObject() + { + Bitmap bmp = new(Showcase.Width, Showcase.Height); + Graphics gr = Graphics.FromImage(bmp); + + _cruiser?.SetPictureSize(Showcase.Width, Showcase.Height); + _cruiser?.SetPosition(Showcase.Width - 400, Showcase.Height - 120); + _cruiser?.DrawTransport(gr); + Showcase.Image = bmp; + } + + private void Panel_MouseDown(object? sender, MouseEventArgs e) + { + // TODO отправка цвета в Drag&Drop + (sender as Control).DoDragDrop((sender as Control).BackColor, DragDropEffects.Move | DragDropEffects.Copy); + } + + private void BaseAdvLabel_MouseDown(object sender, MouseEventArgs e) + { + (sender as Label)?.DoDragDrop((sender as Label)?.Name ?? string.Empty, DragDropEffects.Move | DragDropEffects.Copy); + } + + private void PanelObject_DragEnter(object sender, DragEventArgs e) + { + if (e.Data?.GetDataPresent(DataFormats.Text) ?? false) e.Effect = DragDropEffects.Copy; + else e.Effect = DragDropEffects.None; + } + + private void PanelObject_DragDrop(object sender, DragEventArgs e) + { + switch (e.Data?.GetData(DataFormats.Text)?.ToString()) + { + case "BaseLabel": + _cruiser = new DrawningBase((int)SpeedN.Value, (double)WeightN.Value, Color.White); + break; + case "AdvLabel": + Random rn = new Random(); + _cruiser = new DrawningCruiser((int)SpeedN.Value, (double)WeightN.Value, + Color.White, Color.Black,checkBoxHangars.Checked); + // ADD helicopter PAD as NOT DEFAULT - checkBoxPads.Checked [!] + // Convert.ToBoolean(rn.Next(0, 2))); + break; + } + labelMcolor.BackColor = Color.Empty; + labelAcolor.BackColor = Color.Empty; + DrawObject(); + } + + // TODO Реализовать логику смены цветов: основного и дополнительного (для продвинутого объекта) + private void BodyColor_DragEnter(object sender, DragEventArgs e) + { + if (e.Data.GetDataPresent(typeof(Color))) e.Effect = DragDropEffects.Copy; + else e.Effect = DragDropEffects.None; + } + + private void BodyColor_DragDrop(object sender, DragEventArgs e) + { + if (_cruiser != null) + { + _cruiser.EntityTransport.setMainColor((Color)e.Data.GetData(typeof(Color))); + DrawObject(); + } + } + + private void AdditionalColor_DragEnter(object sender, DragEventArgs e) + { + if (_cruiser is DrawningCruiser) + { + if (e.Data.GetDataPresent(typeof(Color))) e.Effect = DragDropEffects.Copy; + else e.Effect = DragDropEffects.None; + } + } + + private void AdditionalColor_DragDrop(object sender, DragEventArgs e) + { + if (_cruiser.EntityTransport is EntityCruiser _ship) + { + _ship.setAdditionalColor((Color)e.Data.GetData(typeof(Color))); + } + DrawObject(); + } + + private void AddButton_Click(object sender, EventArgs e) + { + if (_cruiser != null) + { + shipDelegate?.Invoke(_cruiser); + Close(); + } + } +} diff --git a/ProjectCruiser/EditorForm3.resx b/ProjectCruiser/EditorForm3.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/ProjectCruiser/EditorForm3.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/ProjectCruiser/Entities/EntityBase.cs b/ProjectCruiser/Entities/EntityBase.cs index f9aac46..ba5b0cf 100644 --- a/ProjectCruiser/Entities/EntityBase.cs +++ b/ProjectCruiser/Entities/EntityBase.cs @@ -7,6 +7,11 @@ public class EntityBase public double Weight { get; private set; } // вес public Color MainColor { get; private set; } // основной цвет + public void setMainColor(Color clr) + { + MainColor = clr; + } + // public bool Deckhouse { get; private set; } // салон на верхней палубе public double Step => Speed * 100 / Weight; diff --git a/ProjectCruiser/Entities/EntityCruiser.cs b/ProjectCruiser/Entities/EntityCruiser.cs index 514f8e8..af25267 100644 --- a/ProjectCruiser/Entities/EntityCruiser.cs +++ b/ProjectCruiser/Entities/EntityCruiser.cs @@ -4,6 +4,11 @@ public class EntityCruiser : EntityBase { public Color AdditionalColor { get; private set; } // доп. цвет + public void setAdditionalColor(Color clr) + { + AdditionalColor = clr; + } + // признаки (наличия) public bool HelicopterPads { get; private set; } // вертолетная площадка public bool Hangars { get; private set; } // ангар diff --git a/ProjectCruiser/ServiceForm2.Designer.cs b/ProjectCruiser/ServiceForm2.Designer.cs index ed3cc6a..3a92906 100644 --- a/ProjectCruiser/ServiceForm2.Designer.cs +++ b/ProjectCruiser/ServiceForm2.Designer.cs @@ -29,16 +29,7 @@ private void InitializeComponent() { comboBoxArrList = new ComboBox(); - btnAddBase = new Button(); groupBox = new GroupBox(); - toolPanel = new Panel(); - btnUpdate = new Button(); - btnTest = new Button(); - maskedTextBoxPosition = new MaskedTextBox(); - btnDelete = new Button(); - btnAddCruiser = new Button(); - btnCreateCompany = new Button(); - pictureBox = new PictureBox(); companyPanel = new Panel(); btnDeleteCollection = new Button(); listBox = new ListBox(); @@ -47,10 +38,18 @@ rBtnArray = new RadioButton(); maskedTxtBoxCName = new MaskedTextBox(); label = new Label(); + toolPanel = new Panel(); + btnUpdate = new Button(); + btnTest = new Button(); + maskedTextBoxPosition = new MaskedTextBox(); + btnDelete = new Button(); + btnAddCruiser = new Button(); + btnCreateCompany = new Button(); + pictureBox = new PictureBox(); groupBox.SuspendLayout(); + companyPanel.SuspendLayout(); toolPanel.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); - companyPanel.SuspendLayout(); SuspendLayout(); // // comboBoxArrList @@ -64,17 +63,6 @@ comboBoxArrList.TabIndex = 0; comboBoxArrList.SelectedIndexChanged += SelectorCompany_SelectedIndexChanged; // - // btnAddBase - // - btnAddBase.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - btnAddBase.Location = new Point(17, 13); - btnAddBase.Name = "btnAddBase"; - btnAddBase.Size = new Size(192, 43); - btnAddBase.TabIndex = 1; - btnAddBase.Text = "Add ship"; - btnAddBase.UseVisualStyleBackColor = true; - btnAddBase.Click += btnAddBase_Click; - // // groupBox // groupBox.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; @@ -89,6 +77,89 @@ groupBox.TabStop = false; groupBox.Text = "Tool panel"; // + // companyPanel + // + companyPanel.Controls.Add(btnDeleteCollection); + companyPanel.Controls.Add(listBox); + companyPanel.Controls.Add(btnAddCollection); + companyPanel.Controls.Add(rBtnList); + companyPanel.Controls.Add(rBtnArray); + companyPanel.Controls.Add(maskedTxtBoxCName); + companyPanel.Controls.Add(label); + companyPanel.Location = new Point(17, 91); + companyPanel.Name = "companyPanel"; + companyPanel.Size = new Size(243, 391); + companyPanel.TabIndex = 7; + // + // btnDeleteCollection + // + btnDeleteCollection.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + btnDeleteCollection.Location = new Point(15, 312); + btnDeleteCollection.Name = "btnDeleteCollection"; + btnDeleteCollection.Size = new Size(214, 73); + btnDeleteCollection.TabIndex = 11; + btnDeleteCollection.Text = "Remove Collection"; + btnDeleteCollection.UseVisualStyleBackColor = true; + btnDeleteCollection.Click += btnCollectionDel_Click; + // + // listBox + // + listBox.FormattingEnabled = true; + listBox.Location = new Point(16, 174); + listBox.Name = "listBox"; + listBox.Size = new Size(214, 132); + listBox.TabIndex = 10; + // + // btnAddCollection + // + btnAddCollection.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + btnAddCollection.Location = new Point(15, 119); + btnAddCollection.Name = "btnAddCollection"; + btnAddCollection.Size = new Size(214, 50); + btnAddCollection.TabIndex = 7; + btnAddCollection.Text = "Add Collection"; + btnAddCollection.UseVisualStyleBackColor = true; + btnAddCollection.Click += btnCollectionAdd_Click; + // + // rBtnList + // + rBtnList.AutoSize = true; + rBtnList.Location = new Point(150, 80); + rBtnList.Name = "rBtnList"; + rBtnList.Size = new Size(80, 36); + rBtnList.TabIndex = 9; + rBtnList.TabStop = true; + rBtnList.Text = "List"; + rBtnList.UseVisualStyleBackColor = true; + // + // rBtnArray + // + rBtnArray.AutoSize = true; + rBtnArray.Location = new Point(16, 80); + rBtnArray.Name = "rBtnArray"; + rBtnArray.Size = new Size(100, 36); + rBtnArray.TabIndex = 8; + rBtnArray.TabStop = true; + rBtnArray.Text = "Array"; + rBtnArray.UseVisualStyleBackColor = true; + // + // maskedTxtBoxCName + // + maskedTxtBoxCName.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + maskedTxtBoxCName.Location = new Point(16, 40); + maskedTxtBoxCName.Name = "maskedTxtBoxCName"; + maskedTxtBoxCName.Size = new Size(214, 39); + maskedTxtBoxCName.TabIndex = 7; + // + // label + // + label.AutoSize = true; + label.Location = new Point(29, 5); + label.Name = "label"; + label.Size = new Size(188, 32); + label.TabIndex = 0; + label.Text = "Collection name"; + // // toolPanel // toolPanel.Controls.Add(btnUpdate); @@ -96,19 +167,18 @@ toolPanel.Controls.Add(maskedTextBoxPosition); toolPanel.Controls.Add(btnDelete); toolPanel.Controls.Add(btnAddCruiser); - toolPanel.Controls.Add(btnAddBase); toolPanel.Enabled = false; - toolPanel.Location = new Point(26, 593); + toolPanel.Location = new Point(26, 567); toolPanel.Name = "toolPanel"; - toolPanel.Size = new Size(226, 377); + toolPanel.Size = new Size(226, 317); toolPanel.TabIndex = 13; // // btnUpdate // btnUpdate.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - btnUpdate.Location = new Point(17, 315); + btnUpdate.Location = new Point(16, 257); btnUpdate.Name = "btnUpdate"; - btnUpdate.Size = new Size(192, 49); + btnUpdate.Size = new Size(192, 41); btnUpdate.TabIndex = 6; btnUpdate.Text = "Update"; btnUpdate.UseVisualStyleBackColor = true; @@ -117,9 +187,9 @@ // btnTest // btnTest.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - btnTest.Location = new Point(17, 224); + btnTest.Location = new Point(17, 162); btnTest.Name = "btnTest"; - btnTest.Size = new Size(192, 85); + btnTest.Size = new Size(192, 89); btnTest.TabIndex = 5; btnTest.Text = "Choose\r\nfor testing"; btnTest.UseVisualStyleBackColor = true; @@ -128,7 +198,7 @@ // maskedTextBoxPosition // maskedTextBoxPosition.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - maskedTextBoxPosition.Location = new Point(17, 119); + maskedTextBoxPosition.Location = new Point(17, 68); maskedTextBoxPosition.Mask = "00"; maskedTextBoxPosition.Name = "maskedTextBoxPosition"; maskedTextBoxPosition.Size = new Size(192, 39); @@ -138,9 +208,9 @@ // btnDelete // btnDelete.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - btnDelete.Location = new Point(17, 170); + btnDelete.Location = new Point(16, 113); btnDelete.Name = "btnDelete"; - btnDelete.Size = new Size(192, 48); + btnDelete.Size = new Size(192, 43); btnDelete.TabIndex = 4; btnDelete.Text = "Delete"; btnDelete.UseVisualStyleBackColor = true; @@ -149,22 +219,22 @@ // btnAddCruiser // btnAddCruiser.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - btnAddCruiser.Location = new Point(17, 62); + btnAddCruiser.Location = new Point(17, 13); btnAddCruiser.Name = "btnAddCruiser"; - btnAddCruiser.Size = new Size(192, 51); + btnAddCruiser.Size = new Size(192, 49); btnAddCruiser.TabIndex = 2; btnAddCruiser.Text = "Add cruiser"; btnAddCruiser.UseVisualStyleBackColor = true; - btnAddCruiser.Click += btnAddAdvanced_Click; + btnAddCruiser.Click += btnAddTransport_Click; // // btnCreateCompany // btnCreateCompany.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - btnCreateCompany.Location = new Point(17, 526); + btnCreateCompany.Location = new Point(16, 488); btnCreateCompany.Name = "btnCreateCompany"; - btnCreateCompany.Size = new Size(243, 61); + btnCreateCompany.Size = new Size(245, 73); btnCreateCompany.TabIndex = 12; - btnCreateCompany.Text = "Create Company"; + btnCreateCompany.Text = "Create or switch to Company"; btnCreateCompany.UseVisualStyleBackColor = true; btnCreateCompany.Click += btnCreateCompany_Click; // @@ -177,89 +247,6 @@ pictureBox.TabIndex = 3; pictureBox.TabStop = false; // - // companyPanel - // - companyPanel.Controls.Add(btnDeleteCollection); - companyPanel.Controls.Add(listBox); - companyPanel.Controls.Add(btnAddCollection); - companyPanel.Controls.Add(rBtnList); - companyPanel.Controls.Add(rBtnArray); - companyPanel.Controls.Add(maskedTxtBoxCName); - companyPanel.Controls.Add(label); - companyPanel.Location = new Point(17, 91); - companyPanel.Name = "companyPanel"; - companyPanel.Size = new Size(243, 429); - companyPanel.TabIndex = 7; - // - // btnDeleteCollection - // - btnDeleteCollection.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - btnDeleteCollection.Location = new Point(15, 371); - btnDeleteCollection.Name = "btnDeleteCollection"; - btnDeleteCollection.Size = new Size(214, 43); - btnDeleteCollection.TabIndex = 11; - btnDeleteCollection.Text = "Remove Collection"; - btnDeleteCollection.UseVisualStyleBackColor = true; - btnDeleteCollection.Click += btnCollectionDel_Click; - // - // listBox - // - listBox.FormattingEnabled = true; - listBox.Location = new Point(16, 199); - listBox.Name = "listBox"; - listBox.Size = new Size(214, 164); - listBox.TabIndex = 10; - // - // btnAddCollection - // - btnAddCollection.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - btnAddCollection.Location = new Point(15, 130); - btnAddCollection.Name = "btnAddCollection"; - btnAddCollection.Size = new Size(214, 61); - btnAddCollection.TabIndex = 7; - btnAddCollection.Text = "Add Collection"; - btnAddCollection.UseVisualStyleBackColor = true; - btnAddCollection.Click += btnCollectionAdd_Click; - // - // rBtnList - // - rBtnList.AutoSize = true; - rBtnList.Location = new Point(150, 88); - rBtnList.Name = "rBtnList"; - rBtnList.Size = new Size(80, 36); - rBtnList.TabIndex = 9; - rBtnList.TabStop = true; - rBtnList.Text = "List"; - rBtnList.UseVisualStyleBackColor = true; - // - // rBtnArray - // - rBtnArray.AutoSize = true; - rBtnArray.Location = new Point(16, 88); - rBtnArray.Name = "rBtnArray"; - rBtnArray.Size = new Size(100, 36); - rBtnArray.TabIndex = 8; - rBtnArray.TabStop = true; - rBtnArray.Text = "Array"; - rBtnArray.UseVisualStyleBackColor = true; - // - // maskedTxtBoxCName - // - maskedTxtBoxCName.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - maskedTxtBoxCName.Location = new Point(16, 43); - maskedTxtBoxCName.Name = "maskedTxtBoxCName"; - maskedTxtBoxCName.Size = new Size(214, 39); - maskedTxtBoxCName.TabIndex = 7; - // - // label - // - label.AutoSize = true; - label.Location = new Point(29, 6); - label.Name = "label"; - label.Size = new Size(188, 32); - label.TabIndex = 0; - label.Text = "Collection name"; - // // ServiceForm2 // AutoScaleDimensions = new SizeF(13F, 32F); @@ -270,18 +257,17 @@ Name = "ServiceForm2"; Text = "ServiceForm2"; groupBox.ResumeLayout(false); + companyPanel.ResumeLayout(false); + companyPanel.PerformLayout(); toolPanel.ResumeLayout(false); toolPanel.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); - companyPanel.ResumeLayout(false); - companyPanel.PerformLayout(); ResumeLayout(false); } #endregion private ComboBox comboBoxArrList; - private Button btnAddBase; private GroupBox groupBox; private Button btnAddCruiser; private Button btnUpdate; diff --git a/ProjectCruiser/ServiceForm2.cs b/ProjectCruiser/ServiceForm2.cs index 02bbd58..fb6f4d7 100644 --- a/ProjectCruiser/ServiceForm2.cs +++ b/ProjectCruiser/ServiceForm2.cs @@ -1,9 +1,5 @@ -using System.Collections.Generic; -using System.Windows.Forms; -using System.Xml.Linq; -using ProjectCruiser.CollectionGenericObj; +using ProjectCruiser.CollectionGenericObj; using ProjectCruiser.DrawningSamples; -using static System.Windows.Forms.VisualStyles.VisualStyleElement; namespace ProjectCruiser; public partial class ServiceForm2 : Form @@ -22,16 +18,6 @@ public partial class ServiceForm2 : Form // Выбор компании private void SelectorCompany_SelectedIndexChanged(object sender, EventArgs e) { - /* - switch (comboBoxArrList.Text) - { - case "Storage": - _company = new ShipSharingService(pictureBox.Width, pictureBox.Height, - new ArrayGenObj()); - break; - } - */ - toolPanel.Enabled = false; } @@ -47,40 +33,23 @@ public partial class ServiceForm2 : Form return cl; } - // Добавление обычного корабля - private void btnAddBase_Click(object sender, EventArgs e) => - CreateObject(nameof(DrawningBase)); - - // Добавление продвинутого - private void btnAddAdvanced_Click(object sender, EventArgs e) => - CreateObject(nameof(DrawningCruiser)); + // Добавление корабля + private void btnAddTransport_Click(object sender, EventArgs e) + { + EditorForm3 form3 = new(); + // TODO передать метод : + form3.AddEvent(CreateObject); + form3.Show(); + } // Создание объекта класса-перемещения - private void CreateObject(string type) + private void CreateObject(DrawningBase? ship) { - if (_company == null) + if (_company == null || ship == null) { return; } - Random random = new(); - DrawningBase drawningCar; - - switch (type) - { - case nameof(DrawningBase): - drawningCar = new DrawningBase(random.Next(100, 300), - random.Next(1000, 3000), pickColor(random)); - break; - - case nameof(DrawningCruiser): - drawningCar = new DrawningCruiser(random.Next(100, 300), - random.Next(1000, 3000), pickColor(random), pickColor(random), - Convert.ToBoolean(random.Next(0, 2))); - break; - default: - return; - } - if (_company + drawningCar != -1) + if (_company + ship != -1) { MessageBox.Show("> Object was added"); pictureBox.Image = _company.Show(); diff --git a/ProjectCruiser/ShipDelegate.cs b/ProjectCruiser/ShipDelegate.cs new file mode 100644 index 0000000..5f320a0 --- /dev/null +++ b/ProjectCruiser/ShipDelegate.cs @@ -0,0 +1,6 @@ +using ProjectCruiser.DrawningSamples; + +namespace ProjectCruiser +{ + public delegate void ShipDelegate(DrawningBase transport); +} -- 2.25.1 From f3a64bc61701e498ae839c43f7004aa201337a05 Mon Sep 17 00:00:00 2001 From: DelphyAlmond Date: Sat, 15 Jun 2024 10:03:23 +0400 Subject: [PATCH 09/13] delegates --- .../DrawningSamples/DrawningCruiser.cs | 20 ++++++++++--------- ProjectCruiser/EditorForm3.cs | 9 ++------- ProjectCruiser/Entities/EntityCruiser.cs | 4 ++-- ProjectCruiser/OceanForm1.cs | 2 +- 4 files changed, 16 insertions(+), 19 deletions(-) diff --git a/ProjectCruiser/DrawningSamples/DrawningCruiser.cs b/ProjectCruiser/DrawningSamples/DrawningCruiser.cs index 4f3f56e..8b1c8c7 100644 --- a/ProjectCruiser/DrawningSamples/DrawningCruiser.cs +++ b/ProjectCruiser/DrawningSamples/DrawningCruiser.cs @@ -6,17 +6,17 @@ public class DrawningCruiser : DrawningBase { // Инициализация свойств (все параметры класса (сущности)) public DrawningCruiser(int speed, double weight, Color bodyColor, - Color additionalColor, bool hangars) : base(302, 42) - // all additional featchures 'inside' object, so size remains + Color additionalColor, bool pad, bool hangars) : base(302, 42) { EntityTransport = new EntityCruiser(speed, weight, - bodyColor, additionalColor, hangars); + bodyColor, additionalColor, pad, hangars); } public override void DrawTransport(Graphics g) { - if (EntityTransport == null || EntityTransport is not EntityCruiser ship || - !_startPosX.HasValue || !_startPosY.HasValue) // [ !!! ] :O + if (EntityTransport == null || + EntityTransport is not EntityCruiser ship || + !_startPosX.HasValue || !_startPosY.HasValue) { return; } @@ -31,10 +31,12 @@ public class DrawningCruiser : DrawningBase base.DrawTransport(g); - // вертолетная площадка - default TRUE now - g.DrawEllipse(pen, _startPosX.Value + 170, _startPosY.Value + 11, 20, 20); - g.FillEllipse(PadBrush, _startPosX.Value + 170, _startPosY.Value + 11, 20, 20); - + // вертолетная площадка - non-default + if (ship.HelicopterPads) + { + g.DrawEllipse(pen, _startPosX.Value + 170, _startPosY.Value + 11, 20, 20); + g.FillEllipse(PadBrush, _startPosX.Value + 170, _startPosY.Value + 11, 20, 20); + } // ангар(ы) if (ship.Hangars) { diff --git a/ProjectCruiser/EditorForm3.cs b/ProjectCruiser/EditorForm3.cs index 949cbf5..269f27b 100644 --- a/ProjectCruiser/EditorForm3.cs +++ b/ProjectCruiser/EditorForm3.cs @@ -28,7 +28,6 @@ public partial class EditorForm3 : Form { if (shipDelegate == null) shipDelegate = del; else shipDelegate += del; - //shipDelegate += del; } private void DrawObject() @@ -69,9 +68,7 @@ public partial class EditorForm3 : Form case "AdvLabel": Random rn = new Random(); _cruiser = new DrawningCruiser((int)SpeedN.Value, (double)WeightN.Value, - Color.White, Color.Black,checkBoxHangars.Checked); - // ADD helicopter PAD as NOT DEFAULT - checkBoxPads.Checked [!] - // Convert.ToBoolean(rn.Next(0, 2))); + Color.White, Color.Black, checkBoxPads.Checked, checkBoxHangars.Checked); break; } labelMcolor.BackColor = Color.Empty; @@ -79,13 +76,12 @@ public partial class EditorForm3 : Form DrawObject(); } - // TODO Реализовать логику смены цветов: основного и дополнительного (для продвинутого объекта) + // Логика смены цветов: основного и дополнительного (для продвинутого объекта) private void BodyColor_DragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(typeof(Color))) e.Effect = DragDropEffects.Copy; else e.Effect = DragDropEffects.None; } - private void BodyColor_DragDrop(object sender, DragEventArgs e) { if (_cruiser != null) @@ -103,7 +99,6 @@ public partial class EditorForm3 : Form else e.Effect = DragDropEffects.None; } } - private void AdditionalColor_DragDrop(object sender, DragEventArgs e) { if (_cruiser.EntityTransport is EntityCruiser _ship) diff --git a/ProjectCruiser/Entities/EntityCruiser.cs b/ProjectCruiser/Entities/EntityCruiser.cs index af25267..e04588a 100644 --- a/ProjectCruiser/Entities/EntityCruiser.cs +++ b/ProjectCruiser/Entities/EntityCruiser.cs @@ -14,11 +14,11 @@ public class EntityCruiser : EntityBase public bool Hangars { get; private set; } // ангар public EntityCruiser(int speed, double weight, Color mainc, - Color additionalColor, bool hangars) + Color additionalColor, bool pad, bool hangars) : base(speed, weight, mainc) { AdditionalColor = additionalColor; - // HelicopterPads = pads; - default TRUE now for Advanced obj + HelicopterPads = pad; // non-default now for editor Form3 Hangars = hangars; } } diff --git a/ProjectCruiser/OceanForm1.cs b/ProjectCruiser/OceanForm1.cs index e8b217f..3c9e341 100644 --- a/ProjectCruiser/OceanForm1.cs +++ b/ProjectCruiser/OceanForm1.cs @@ -68,7 +68,7 @@ namespace ProjectCruiser random.Next(100, 300), random.Next(1000, 3000), Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), - Convert.ToBoolean(random.Next(0, 2))); + Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2))); break; default: -- 2.25.1 From 86e57edbc89c7028ad7e3e7de38ad48943fcbf63 Mon Sep 17 00:00:00 2001 From: DelphyAlmond Date: Sat, 15 Jun 2024 13:28:42 +0400 Subject: [PATCH 10/13] In process : fix loading from txt --- .../CollectionGenericObj/AbstractCompany.cs | 2 +- .../CollectionGenericObj/ArrayGenObj.cs | 16 +- .../CollectionGenericObj/ICollectionGenObj.cs | 8 +- .../CollectionGenericObj/ListGenObj.cs | 16 +- .../CollectionGenericObj/StorageCollection.cs | 154 ++++++++++++++++-- .../DrawningSamples/DrawningBase.cs | 4 +- .../DrawningSamples/DrawningCruiser.cs | 6 +- .../DrawningSamples/ExtentionDrShip.cs | 41 +++++ ProjectCruiser/EditorForm3.cs | 6 +- ProjectCruiser/Entities/EntityBase.cs | 19 ++- ProjectCruiser/Entities/EntityCruiser.cs | 22 +++ ProjectCruiser/OceanForm1.cs | 7 +- ProjectCruiser/ServiceForm2.Designer.cs | 77 ++++++++- ProjectCruiser/ServiceForm2.cs | 49 ++++-- ProjectCruiser/ServiceForm2.resx | 9 + 15 files changed, 389 insertions(+), 47 deletions(-) create mode 100644 ProjectCruiser/DrawningSamples/ExtentionDrShip.cs diff --git a/ProjectCruiser/CollectionGenericObj/AbstractCompany.cs b/ProjectCruiser/CollectionGenericObj/AbstractCompany.cs index d94f1c8..5b98774 100644 --- a/ProjectCruiser/CollectionGenericObj/AbstractCompany.cs +++ b/ProjectCruiser/CollectionGenericObj/AbstractCompany.cs @@ -26,7 +26,7 @@ public abstract class AbstractCompany _pictureWidth = picWidth; _pictureHeight = picHeight; _collection = collection; - _collection.SetMaxCount = GetMaxCount; + _collection.MaxCount = GetMaxCount; } // Перегрузка оператора сложения для класса diff --git a/ProjectCruiser/CollectionGenericObj/ArrayGenObj.cs b/ProjectCruiser/CollectionGenericObj/ArrayGenObj.cs index 620dcc8..1d5ffd3 100644 --- a/ProjectCruiser/CollectionGenericObj/ArrayGenObj.cs +++ b/ProjectCruiser/CollectionGenericObj/ArrayGenObj.cs @@ -1,4 +1,5 @@ -namespace ProjectCruiser.CollectionGenericObj; + +namespace ProjectCruiser.CollectionGenericObj; public class ArrayGenObj : ICollectionGenObj where T : class @@ -6,8 +7,9 @@ public class ArrayGenObj : ICollectionGenObj // Массив объектов, которые храним private T?[] _collection; public int Count => _collection.Length; - public int SetMaxCount + public int MaxCount { + get { return _collection.Length; } set { if (value > 0) @@ -18,7 +20,7 @@ public class ArrayGenObj : ICollectionGenObj } } - // public int SetMaxCount { set { if (value > 0) { _collection = new T?[value]; } } } + public CollectionType GetCollectionType => CollectionType.Array; public ArrayGenObj() { @@ -90,5 +92,13 @@ public class ArrayGenObj : ICollectionGenObj } return null; } + + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Length; ++i) + { + yield return _collection[i]; + } + } } diff --git a/ProjectCruiser/CollectionGenericObj/ICollectionGenObj.cs b/ProjectCruiser/CollectionGenericObj/ICollectionGenObj.cs index d87998c..4af2547 100644 --- a/ProjectCruiser/CollectionGenericObj/ICollectionGenObj.cs +++ b/ProjectCruiser/CollectionGenericObj/ICollectionGenObj.cs @@ -6,7 +6,7 @@ public interface ICollectionGenObj where T : class int Count { get; } // Установка max кол-ва элементов - int SetMaxCount { set; } + int MaxCount { set; get; } /// Добавление объекта в коллекцию /// Добавляемый объект @@ -21,4 +21,10 @@ public interface ICollectionGenObj where T : class // Получение объекта по позиции T? GetItem(int position); + + // Получение типа коллекции + CollectionType GetCollectionType { get; } + + // Получение объектов коллекции по одному + IEnumerable GetItems(); } diff --git a/ProjectCruiser/CollectionGenericObj/ListGenObj.cs b/ProjectCruiser/CollectionGenericObj/ListGenObj.cs index 0b33867..1691879 100644 --- a/ProjectCruiser/CollectionGenericObj/ListGenObj.cs +++ b/ProjectCruiser/CollectionGenericObj/ListGenObj.cs @@ -14,7 +14,13 @@ public class ListGenObj : ICollectionGenObj private int _maxCount; public int Count => _collection.Count; - public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } + public int MaxCount + { + get { return _collection.Count; } + set { if (value > 0) { _maxCount = value; } } + } + + public CollectionType GetCollectionType => CollectionType.List; public ListGenObj() { @@ -67,4 +73,12 @@ public class ListGenObj : ICollectionGenObj _collection.RemoveAt(position); return item; } + + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Count; ++i) + { + yield return _collection[i]; + } + } } diff --git a/ProjectCruiser/CollectionGenericObj/StorageCollection.cs b/ProjectCruiser/CollectionGenericObj/StorageCollection.cs index cd62ac5..c37c0c2 100644 --- a/ProjectCruiser/CollectionGenericObj/StorageCollection.cs +++ b/ProjectCruiser/CollectionGenericObj/StorageCollection.cs @@ -1,8 +1,19 @@ -namespace ProjectCruiser.CollectionGenericObj; +using System.Text; +using ProjectCruiser.DrawningSamples; + +namespace ProjectCruiser.CollectionGenericObj; public class StorageCollection -where T : class + where T : DrawningBase { + // Разделитель для записи ключа и значения элемента словаря + private readonly string _separatorForKeyValue = "|"; + // Разделитель для записей коллекции данных в файл + private readonly string _separatorItems = ";"; + + // Ключевое слово, с которого должен начинаться файл + private readonly string _collectionKey = "CollectionsStorage"; + // Словарь (хранилище) с коллекциями < name, type (class) > readonly Dictionary> _storages; @@ -14,9 +25,7 @@ where T : class _storages = new Dictionary>(); } - /// Добавление коллекции в хранилище - /// Название коллекции - /// тип коллекции + // Добавление коллекции в хранилище public void AddCollection(string name, CollectionType collType) { if (name == null || _storages.ContainsKey(name) @@ -25,27 +34,152 @@ where T : class return; } + ICollectionGenObj collection = CreateCollection(collType); + _storages.Add(name, collection); + + /* switch (collType) { case CollectionType.List: _storages.Add(name, new ListGenObj()); break; - // _storages[name] = new ListGenericObjects(); break; [*] - case CollectionType.Array: _storages.Add(name, new ArrayGenObj()); break; } + */ } - /// Удаление коллекции ( по ключу-строке - её имени ) - /// Название коллекции + // Удаление коллекции ( по ключу-строке - её имени ) public void DelCollection(string name) { if (_storages.ContainsKey(name)) _storages.Remove(name); return; } - /// Доступ к коллекции ( по ключу-строке - её имени ) + // Доступ к коллекции ( по ключу-строке - её имени ) public ICollectionGenObj? this[string name] { get => _storages.ContainsKey(name) ? _storages[name] : null; } + + /// Сохранение информации по автомобилям в хранилище в файл + /// Путь и имя файла + /// true - сохранение прошло успешно, + /// false - ошибка при сохранении данных + 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> value in _storages) + { + sb.Append(Environment.NewLine); // не сохраняем пустые коллекции + if (value.Value.Count == 0) { continue; } + + sb.Append(value.Key); + sb.Append(_separatorForKeyValue); + sb.Append(value.Value.GetCollectionType); + sb.Append(_separatorForKeyValue); + sb.Append(value.Value.MaxCount); + sb.Append(_separatorForKeyValue); + + foreach (T? item in value.Value.GetItems()) + { + string data = item?.GetDataForSave() ?? string.Empty; + if (string.IsNullOrEmpty(data)) + { + continue; + } + sb.Append(data); + sb.Append(_separatorItems); + } + } + + using FileStream fs = new(filename, FileMode.Create); + byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString()); + fs.Write(info, 0, info.Length); + return true; + } + + // Создание коллекции по типу + private static ICollectionGenObj? CreateCollection(CollectionType collectionType) + { + return collectionType switch + { + CollectionType.Array => new ArrayGenObj(), + CollectionType.List => new ListGenObj(), + _ => null, + }; + } + + // Загрузка информации по кораблям в хранилище из файла + public bool LoadData(string filename) + { + if (!File.Exists(filename)) + { + return false; + } + + string bufferTextFromFile = ""; + + using (FileStream fs = new(filename, FileMode.Open)) + { + byte[] b = new byte[fs.Length]; + UTF8Encoding temp = new(true); + while (fs.Read(b, 0, b.Length) > 0) + { + bufferTextFromFile += temp.GetString(b); + } + } + + string[] strs = bufferTextFromFile.Split( + new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); + + if (strs == null || strs.Length == 0) + { + return false; + } + if (!strs[0].Equals(_collectionKey)) + { + //если нет такой записи, то это не те данные + return false; + } + + _storages.Clear(); + foreach (string data in strs) + { + string[] record = data.Split(_separatorForKeyValue, + StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 4) // > + // key | collType | maxcount | all next inf > 4 + { + continue; + } + CollectionType collectionType = + (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); + ICollectionGenObj? collection = StorageCollection.CreateCollection(collectionType); + if (collection == null) + { + return false; + } + + collection.MaxCount = Convert.ToInt32(record[2]); + string[] set = record[3].Split(_separatorItems, + StringSplitOptions.RemoveEmptyEntries); + foreach (string elem in set) + { + if (elem?.CreateDrawningCar() is T car) + { + if (!(collection.Insert(car) == -1)) + { + return false; + } + } + } + _storages.Add(record[0], collection); + } + return true; + } } diff --git a/ProjectCruiser/DrawningSamples/DrawningBase.cs b/ProjectCruiser/DrawningSamples/DrawningBase.cs index 4b7884f..7812c65 100644 --- a/ProjectCruiser/DrawningSamples/DrawningBase.cs +++ b/ProjectCruiser/DrawningSamples/DrawningBase.cs @@ -14,9 +14,9 @@ public class DrawningBase private readonly int _drawningHeight = 42; // Высота прорисовки автомобиля // Инициализация свойств (теперь через конструктор) - public DrawningBase(int speed, double weight, Color bodyColor) : this() + public DrawningBase(EntityBase ship) : this() { - EntityTransport = new EntityBase(speed, weight, bodyColor); + EntityTransport = ship; } private DrawningBase() diff --git a/ProjectCruiser/DrawningSamples/DrawningCruiser.cs b/ProjectCruiser/DrawningSamples/DrawningCruiser.cs index 8b1c8c7..faebb2b 100644 --- a/ProjectCruiser/DrawningSamples/DrawningCruiser.cs +++ b/ProjectCruiser/DrawningSamples/DrawningCruiser.cs @@ -5,11 +5,9 @@ namespace ProjectCruiser.DrawningSamples; public class DrawningCruiser : DrawningBase { // Инициализация свойств (все параметры класса (сущности)) - public DrawningCruiser(int speed, double weight, Color bodyColor, - Color additionalColor, bool pad, bool hangars) : base(302, 42) + public DrawningCruiser(EntityCruiser ship) : base((EntityBase)ship) { - EntityTransport = new EntityCruiser(speed, weight, - bodyColor, additionalColor, pad, hangars); + EntityTransport = ship; } public override void DrawTransport(Graphics g) diff --git a/ProjectCruiser/DrawningSamples/ExtentionDrShip.cs b/ProjectCruiser/DrawningSamples/ExtentionDrShip.cs new file mode 100644 index 0000000..a8990c1 --- /dev/null +++ b/ProjectCruiser/DrawningSamples/ExtentionDrShip.cs @@ -0,0 +1,41 @@ +using ProjectCruiser.Entities; +namespace ProjectCruiser.DrawningSamples; +public static class ExtentionDrShip +{ + // Разделитель для записи информации по объекту в файл + private static readonly string _separatorForObject = ":"; + + // Создание объекта из строки + public static DrawningBase? CreateDrawningCar(this string info) + { + string[] strs = info.Split(_separatorForObject); + + EntityBase? ship = EntityCruiser.CreateEntity(strs); + if (ship != null) + { + return new DrawningCruiser((EntityCruiser)ship); + } + + ship = EntityBase.CreateEntity(strs); + if (ship != null) + { + return new DrawningBase(ship); + } + + return null; + } + + // Получение данных для сохранения в файл + public static string GetDataForSave(this DrawningBase drShip) + // метод расширения за счёт ключевого слова 'this' + // вызов метода достигается не через имя класса, + // а при вызове у объекта типа DrawningBase [*] + { + string[]? array = drShip?.EntityTransport?.GetStringRepresentation(); + if (array == null) + { + return string.Empty; + } + return string.Join(_separatorForObject, array); + } +} diff --git a/ProjectCruiser/EditorForm3.cs b/ProjectCruiser/EditorForm3.cs index 269f27b..0acc113 100644 --- a/ProjectCruiser/EditorForm3.cs +++ b/ProjectCruiser/EditorForm3.cs @@ -63,12 +63,14 @@ public partial class EditorForm3 : Form switch (e.Data?.GetData(DataFormats.Text)?.ToString()) { case "BaseLabel": - _cruiser = new DrawningBase((int)SpeedN.Value, (double)WeightN.Value, Color.White); + EntityBase ship = new EntityBase((int)SpeedN.Value, (double)WeightN.Value, Color.White); + _cruiser = new DrawningBase(ship); break; case "AdvLabel": Random rn = new Random(); - _cruiser = new DrawningCruiser((int)SpeedN.Value, (double)WeightN.Value, + EntityCruiser cruiser = new EntityCruiser((int)SpeedN.Value, (double)WeightN.Value, Color.White, Color.Black, checkBoxPads.Checked, checkBoxHangars.Checked); + _cruiser = new DrawningCruiser(cruiser); break; } labelMcolor.BackColor = Color.Empty; diff --git a/ProjectCruiser/Entities/EntityBase.cs b/ProjectCruiser/Entities/EntityBase.cs index ba5b0cf..fda56bf 100644 --- a/ProjectCruiser/Entities/EntityBase.cs +++ b/ProjectCruiser/Entities/EntityBase.cs @@ -24,9 +24,26 @@ public class EntityBase Speed = speed; Weight = weight; MainColor = mainc; - // Deckhouse = deckhouse; values[0] = rn.Next(1, 4); values[1] = rn.Next(5, 10); values[2] = rn.Next(1, 3); } + + // Получение массива строк со значениями свойств + // объекта : тип (название класса), скорость, вес, осн. цвет [*] + public virtual string[] GetStringRepresentation() + { + return new[] { nameof(EntityBase), Speed.ToString(), + Weight.ToString(), MainColor.Name }; + } + + // decoding string to object + public static EntityBase? CreateEntity(string[] parameters) + { + if (parameters.Length != 4 || parameters.Length == 0 || + parameters[0] != "EntityBase") return null; + + return new EntityBase(Convert.ToInt32(parameters[1]), + Convert.ToDouble(parameters[2]), Color.FromName(parameters[3])); + } } diff --git a/ProjectCruiser/Entities/EntityCruiser.cs b/ProjectCruiser/Entities/EntityCruiser.cs index e04588a..4e7bf03 100644 --- a/ProjectCruiser/Entities/EntityCruiser.cs +++ b/ProjectCruiser/Entities/EntityCruiser.cs @@ -21,4 +21,26 @@ public class EntityCruiser : EntityBase HelicopterPads = pad; // non-default now for editor Form3 Hangars = hangars; } + + // Получение массива строк со значениями свойств + // объекта : тип (название класса), скорость, вес, осн. цвет [*], + // доп. цвет, истинность наличия площадки и (,) ангаров. + public virtual string[] GetStringRepresentation() + { + return new[] { nameof(EntityCruiser), Speed.ToString(), + Weight.ToString(), MainColor.Name, AdditionalColor.Name, + HelicopterPads.ToString(), Hangars.ToString()}; + } + + // decoding string to object + public static EntityCruiser? CreateEntity(string[] parameters) + { + if (parameters.Length != 7 || parameters.Length == 0 || + parameters[0] != "EntityCruiser") return null; + + return new EntityCruiser(Convert.ToInt32(parameters[1]), + Convert.ToDouble(parameters[2]), Color.FromName(parameters[3]), + Color.FromName(parameters[4]), Convert.ToBoolean(parameters[5]), + Convert.ToBoolean(parameters[6])); + } } diff --git a/ProjectCruiser/OceanForm1.cs b/ProjectCruiser/OceanForm1.cs index 3c9e341..1e43641 100644 --- a/ProjectCruiser/OceanForm1.cs +++ b/ProjectCruiser/OceanForm1.cs @@ -1,4 +1,5 @@ using ProjectCruiser.DrawningSamples; +using ProjectCruiser.Entities; using ProjectCruiser.MoveStrategy; namespace ProjectCruiser @@ -59,16 +60,18 @@ namespace ProjectCruiser switch (type) { case nameof(DrawningBase): - _drawningCruiser = new DrawningBase(random.Next(100, 300), random.Next(1000, 3000), + EntityBase ship = new EntityBase(random.Next(100, 300), random.Next(1000, 3000), Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256))); + _drawningCruiser = new DrawningBase(ship); break; case nameof(DrawningCruiser): - _drawningCruiser = new DrawningCruiser( + EntityCruiser cruiser = new EntityCruiser( random.Next(100, 300), random.Next(1000, 3000), Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2))); + _drawningCruiser = new DrawningCruiser(cruiser); break; default: diff --git a/ProjectCruiser/ServiceForm2.Designer.cs b/ProjectCruiser/ServiceForm2.Designer.cs index 3a92906..d065feb 100644 --- a/ProjectCruiser/ServiceForm2.Designer.cs +++ b/ProjectCruiser/ServiceForm2.Designer.cs @@ -46,10 +46,17 @@ btnAddCruiser = new Button(); btnCreateCompany = new Button(); pictureBox = new PictureBox(); + menuStrip = new MenuStrip(); + fileToolStripMenuItem = new ToolStripMenuItem(); + saveToolStripMenuItem = new ToolStripMenuItem(); + loadToolStripMenuItem = new ToolStripMenuItem(); + saveFileDialog = new SaveFileDialog(); + openFileDialog = new OpenFileDialog(); groupBox.SuspendLayout(); companyPanel.SuspendLayout(); toolPanel.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); + menuStrip.SuspendLayout(); SuspendLayout(); // // comboBoxArrList @@ -57,7 +64,7 @@ comboBoxArrList.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; comboBoxArrList.FormattingEnabled = true; comboBoxArrList.Items.AddRange(new object[] { "Storage" }); - comboBoxArrList.Location = new Point(17, 41); + comboBoxArrList.Location = new Point(17, 51); comboBoxArrList.Name = "comboBoxArrList"; comboBoxArrList.Size = new Size(241, 40); comboBoxArrList.TabIndex = 0; @@ -70,9 +77,9 @@ groupBox.Controls.Add(toolPanel); groupBox.Controls.Add(btnCreateCompany); groupBox.Controls.Add(comboBoxArrList); - groupBox.Location = new Point(1421, 10); + groupBox.Location = new Point(1421, 47); groupBox.Name = "groupBox"; - groupBox.Size = new Size(273, 986); + groupBox.Size = new Size(273, 934); groupBox.TabIndex = 2; groupBox.TabStop = false; groupBox.Text = "Tool panel"; @@ -86,7 +93,7 @@ companyPanel.Controls.Add(rBtnArray); companyPanel.Controls.Add(maskedTxtBoxCName); companyPanel.Controls.Add(label); - companyPanel.Location = new Point(17, 91); + companyPanel.Location = new Point(17, 98); companyPanel.Name = "companyPanel"; companyPanel.Size = new Size(243, 391); companyPanel.TabIndex = 7; @@ -168,7 +175,7 @@ toolPanel.Controls.Add(btnDelete); toolPanel.Controls.Add(btnAddCruiser); toolPanel.Enabled = false; - toolPanel.Location = new Point(26, 567); + toolPanel.Location = new Point(26, 608); toolPanel.Name = "toolPanel"; toolPanel.Size = new Size(226, 317); toolPanel.TabIndex = 13; @@ -230,9 +237,9 @@ // btnCreateCompany // btnCreateCompany.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - btnCreateCompany.Location = new Point(16, 488); + btnCreateCompany.Location = new Point(16, 510); btnCreateCompany.Name = "btnCreateCompany"; - btnCreateCompany.Size = new Size(245, 73); + btnCreateCompany.Size = new Size(245, 79); btnCreateCompany.TabIndex = 12; btnCreateCompany.Text = "Create or switch to Company"; btnCreateCompany.UseVisualStyleBackColor = true; @@ -241,12 +248,53 @@ // pictureBox // pictureBox.Dock = DockStyle.Left; - pictureBox.Location = new Point(0, 0); + pictureBox.Location = new Point(0, 40); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(1415, 1007); + pictureBox.Size = new Size(1415, 967); pictureBox.TabIndex = 3; pictureBox.TabStop = false; // + // menuStrip + // + menuStrip.ImageScalingSize = new Size(32, 32); + menuStrip.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem }); + menuStrip.Location = new Point(0, 0); + menuStrip.Name = "menuStrip"; + menuStrip.Size = new Size(1700, 40); + menuStrip.TabIndex = 4; + menuStrip.Text = "menuStrip1"; + // + // fileToolStripMenuItem + // + fileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem }); + fileToolStripMenuItem.Name = "fileToolStripMenuItem"; + fileToolStripMenuItem.Size = new Size(71, 36); + fileToolStripMenuItem.Text = "File"; + // + // saveToolStripMenuItem + // + saveToolStripMenuItem.Name = "saveToolStripMenuItem"; + saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S; + saveToolStripMenuItem.Size = new Size(277, 44); + saveToolStripMenuItem.Text = "Save"; + saveToolStripMenuItem.Click += saveToolStripMenuItem_Click; + // + // loadToolStripMenuItem + // + loadToolStripMenuItem.Name = "loadToolStripMenuItem"; + loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L; + loadToolStripMenuItem.Size = new Size(277, 44); + loadToolStripMenuItem.Text = "Load"; + loadToolStripMenuItem.Click += loadToolStripMenuItem_Click; + // + // saveFileDialog + // + saveFileDialog.Filter = "txt file|*.txt"; + // + // openFileDialog + // + openFileDialog.Filter = "txt file|*.txt"; + // // ServiceForm2 // AutoScaleDimensions = new SizeF(13F, 32F); @@ -254,6 +302,8 @@ ClientSize = new Size(1700, 1007); Controls.Add(pictureBox); Controls.Add(groupBox); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Name = "ServiceForm2"; Text = "ServiceForm2"; groupBox.ResumeLayout(false); @@ -262,7 +312,10 @@ toolPanel.ResumeLayout(false); toolPanel.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion @@ -285,5 +338,11 @@ private Button btnDeleteCollection; private Button btnCreateCompany; private Panel toolPanel; + private MenuStrip menuStrip; + private ToolStripMenuItem fileToolStripMenuItem; + private ToolStripMenuItem saveToolStripMenuItem; + private ToolStripMenuItem loadToolStripMenuItem; + private SaveFileDialog saveFileDialog; + private OpenFileDialog openFileDialog; } } \ No newline at end of file diff --git a/ProjectCruiser/ServiceForm2.cs b/ProjectCruiser/ServiceForm2.cs index fb6f4d7..3b0c05f 100644 --- a/ProjectCruiser/ServiceForm2.cs +++ b/ProjectCruiser/ServiceForm2.cs @@ -21,17 +21,7 @@ public partial class ServiceForm2 : Form toolPanel.Enabled = false; } - // Color picker (default : random) - private static Color pickColor(Random r) - { - Color cl = new Color(); - ColorDialog dialog = new(); - - if (dialog.ShowDialog() == DialogResult.OK) cl = dialog.Color; - else Color.FromArgb(r.Next(0, 256), r.Next(0, 256), r.Next(0, 256)); - - return cl; - } + // Color picker (default : random) <...> // Добавление корабля private void btnAddTransport_Click(object sender, EventArgs e) @@ -194,4 +184,41 @@ public partial class ServiceForm2 : Form toolPanel.Enabled = true; // block of buttons at the right bottom RefreshListBoxItems(); } + + // saving to file + private void saveToolStripMenuItem_Click(object sender, EventArgs e) + { + if (saveFileDialog.ShowDialog() == DialogResult.OK) + { + if (_storageCollection.SaveData(saveFileDialog.FileName)) + { + MessageBox.Show(" < Saved succesfully >", + "Result :", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + else + { + MessageBox.Show("< Failed to save >", "Result :", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + // loading from file + private void loadToolStripMenuItem_Click(object sender, EventArgs e) + { + if (openFileDialog.ShowDialog() == DialogResult.OK) + { + if (_storageCollection.LoadData(openFileDialog.FileName)) + { + MessageBox.Show(" < Loaded succesfully >", + "Result :", MessageBoxButtons.OK, MessageBoxIcon.Information); + RefreshListBoxItems(); + } + else + { + MessageBox.Show("< Failed to load >", "Result :", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } } diff --git a/ProjectCruiser/ServiceForm2.resx b/ProjectCruiser/ServiceForm2.resx index af32865..e8405d2 100644 --- a/ProjectCruiser/ServiceForm2.resx +++ b/ProjectCruiser/ServiceForm2.resx @@ -117,4 +117,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 217, 17 + + + 460, 17 + \ No newline at end of file -- 2.25.1 From f575f977b02a8b26ddb693ad4bd896c45764e8e7 Mon Sep 17 00:00:00 2001 From: DelphyAlmond Date: Sat, 15 Jun 2024 18:06:35 +0400 Subject: [PATCH 11/13] files and streams --- .../CollectionGenericObj/ArrayGenObj.cs | 71 +++++++++++-------- .../CollectionGenericObj/ListGenObj.cs | 21 ++++-- .../CollectionGenericObj/StorageCollection.cs | 61 +++++++++------- .../DrawningSamples/ExtentionDrShip.cs | 2 +- ProjectCruiser/Entities/EntityCruiser.cs | 2 +- ProjectCruiser/Program.cs | 1 - 6 files changed, 97 insertions(+), 61 deletions(-) diff --git a/ProjectCruiser/CollectionGenericObj/ArrayGenObj.cs b/ProjectCruiser/CollectionGenericObj/ArrayGenObj.cs index 1d5ffd3..5c56167 100644 --- a/ProjectCruiser/CollectionGenericObj/ArrayGenObj.cs +++ b/ProjectCruiser/CollectionGenericObj/ArrayGenObj.cs @@ -6,16 +6,22 @@ public class ArrayGenObj : ICollectionGenObj { // Массив объектов, которые храним private T?[] _collection; - public int Count => _collection.Length; + + // Максимально допустимое число объектов в массиве + private int _maxCount; + public int Count => _collection.Count(s => s != null); + public int MaxCount { - get { return _collection.Length; } + get { return _maxCount; } set { if (value > 0) { - if (_collection.Length > 0) Array.Resize(ref _collection, value); - else _collection = new T?[value]; + if (_collection.Length == 0) _collection = new T?[value]; + else Array.Resize(ref _collection, value); + + _maxCount = value; } } } @@ -28,7 +34,6 @@ public class ArrayGenObj : ICollectionGenObj } // methods : - public T? GetItem(int index) { if (index > Count || index < 0) @@ -40,8 +45,13 @@ public class ArrayGenObj : ICollectionGenObj public int Insert(T? item) { - // any empty place - for (int i = 0; i < Count; i++) + if (Count >= _maxCount || item == null) + { + return -1; + } + + // any empty place -> fill immediately + for (int i = 0; i < _collection.Length; i++) { if (_collection[i] == null) { @@ -49,53 +59,56 @@ public class ArrayGenObj : ICollectionGenObj return i; } } - return -1; + return Count; } 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) { _collection[index] = item; return index; } - else + int min_diff = 100, firstNullIndex = 100; + + for (int i = 0; i < Count; i++) { - int min_diff = 100, min_index = 100; - - for (int i = 0; i < Count; i++) + if (_collection[i] == null + && min_diff > Math.Abs(index - i)) { - if (_collection[i] == null - && min_diff > Math.Abs(index - i)) - { - min_diff = Math.Abs(index - i); - min_index = i; - } + min_diff = Math.Abs(index - i); + firstNullIndex = i; } - - _collection[min_index] = item; - return min_index; } - return -1; + _collection[firstNullIndex] = item; + return firstNullIndex; } public T? Remove(int index) { - T? item; - if (index < Count && index >= 0) + if (index >= Count || index < 0) + // on the other positions items don't exist { - item = _collection[index]; - _collection[index] = null; - return item; + return null; } - return null; + + T? item = _collection[index]; + _collection[index] = null; + return item; } public IEnumerable GetItems() { - for (int i = 0; i < _collection.Length; ++i) + for (int i = 0; i < MaxCount; ++i) { yield return _collection[i]; } diff --git a/ProjectCruiser/CollectionGenericObj/ListGenObj.cs b/ProjectCruiser/CollectionGenericObj/ListGenObj.cs index 1691879..fd256d3 100644 --- a/ProjectCruiser/CollectionGenericObj/ListGenObj.cs +++ b/ProjectCruiser/CollectionGenericObj/ListGenObj.cs @@ -1,4 +1,6 @@ using System; +using System.Collections; +using System.Collections.Generic; using System.Reflection; namespace ProjectCruiser.CollectionGenericObj; @@ -8,7 +10,7 @@ public class ListGenObj : ICollectionGenObj where T : class { // Список объектов, которые храним - private readonly List _collection; + private List _collection; // Максимально допустимое число объектов в списке private int _maxCount; @@ -16,8 +18,17 @@ public class ListGenObj : ICollectionGenObj public int MaxCount { - get { return _collection.Count; } - set { if (value > 0) { _maxCount = value; } } + get { return _maxCount; } + set + { + if (value > 0) + { + if (_collection.Count == 0) _collection = new List(value); + else _collection.Capacity = value; // instead of resizing + + _maxCount = value; + } + } } public CollectionType GetCollectionType => CollectionType.List; @@ -37,7 +48,7 @@ public class ListGenObj : ICollectionGenObj return _collection[position]; } - public int Insert(T obj) + public int Insert(T? obj) { if (Count >= _maxCount || obj == null) { @@ -48,7 +59,7 @@ public class ListGenObj : ICollectionGenObj return Count; } - public int Insert(T obj, int position) + public int Insert(T? obj, int position) { if (position >= _maxCount || Count >= _maxCount || position < 0 || _collection[position] != null diff --git a/ProjectCruiser/CollectionGenericObj/StorageCollection.cs b/ProjectCruiser/CollectionGenericObj/StorageCollection.cs index c37c0c2..93ae0b4 100644 --- a/ProjectCruiser/CollectionGenericObj/StorageCollection.cs +++ b/ProjectCruiser/CollectionGenericObj/StorageCollection.cs @@ -4,7 +4,7 @@ using ProjectCruiser.DrawningSamples; namespace ProjectCruiser.CollectionGenericObj; public class StorageCollection - where T : DrawningBase + where T : DrawningBase // class { // Разделитель для записи ключа и значения элемента словаря private readonly string _separatorForKeyValue = "|"; @@ -36,14 +36,6 @@ public class StorageCollection ICollectionGenObj collection = CreateCollection(collType); _storages.Add(name, collection); - - /* - switch (collType) - { - case CollectionType.List: _storages.Add(name, new ListGenObj()); break; - case CollectionType.Array: _storages.Add(name, new ArrayGenObj()); break; - } - */ } // Удаление коллекции ( по ключу-строке - её имени ) @@ -53,7 +45,7 @@ public class StorageCollection return; } - // Доступ к коллекции ( по ключу-строке - её имени ) + // Доступ к коллекции ( по ключу-строке - её имени ) - индексатор [!!!] public ICollectionGenObj? this[string name] { get => _storages.ContainsKey(name) ? _storages[name] : null; @@ -72,25 +64,41 @@ public class StorageCollection sb.Append(_collectionKey); // const - foreach (KeyValuePair> value in _storages) + foreach (KeyValuePair> pair in _storages) { sb.Append(Environment.NewLine); // не сохраняем пустые коллекции - if (value.Value.Count == 0) { continue; } + if (pair.Value.Count == 0) { continue; } - sb.Append(value.Key); + sb.Append(pair.Key); sb.Append(_separatorForKeyValue); - sb.Append(value.Value.GetCollectionType); + sb.Append(pair.Value.GetCollectionType); sb.Append(_separatorForKeyValue); - sb.Append(value.Value.MaxCount); + sb.Append(pair.Value.MaxCount); sb.Append(_separatorForKeyValue); - foreach (T? item in value.Value.GetItems()) + 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); } @@ -146,18 +154,22 @@ public class StorageCollection return false; } - _storages.Clear(); - foreach (string data in strs) + string[] companies = new string[strs.Length - 1]; + for (int k = 1; k < strs.Length; k++) { - string[] record = data.Split(_separatorForKeyValue, - StringSplitOptions.RemoveEmptyEntries); + 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]); + CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); ICollectionGenObj? collection = StorageCollection.CreateCollection(collectionType); if (collection == null) { @@ -167,11 +179,12 @@ public class StorageCollection collection.MaxCount = Convert.ToInt32(record[2]); string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + foreach (string elem in set) { - if (elem?.CreateDrawningCar() is T car) + if (elem?.CreateDrawningCar() is T ship) { - if (!(collection.Insert(car) == -1)) + if (collection.Insert(ship) == -1) { return false; } diff --git a/ProjectCruiser/DrawningSamples/ExtentionDrShip.cs b/ProjectCruiser/DrawningSamples/ExtentionDrShip.cs index a8990c1..ad88fac 100644 --- a/ProjectCruiser/DrawningSamples/ExtentionDrShip.cs +++ b/ProjectCruiser/DrawningSamples/ExtentionDrShip.cs @@ -25,7 +25,7 @@ public static class ExtentionDrShip return null; } - // Получение данных для сохранения в файл + // Получение данных для сохранения в файл - - - - - - - public static string GetDataForSave(this DrawningBase drShip) // метод расширения за счёт ключевого слова 'this' // вызов метода достигается не через имя класса, diff --git a/ProjectCruiser/Entities/EntityCruiser.cs b/ProjectCruiser/Entities/EntityCruiser.cs index 4e7bf03..e53bbe9 100644 --- a/ProjectCruiser/Entities/EntityCruiser.cs +++ b/ProjectCruiser/Entities/EntityCruiser.cs @@ -25,7 +25,7 @@ public class EntityCruiser : EntityBase // Получение массива строк со значениями свойств // объекта : тип (название класса), скорость, вес, осн. цвет [*], // доп. цвет, истинность наличия площадки и (,) ангаров. - public virtual string[] GetStringRepresentation() + public override string[] GetStringRepresentation() // :O { return new[] { nameof(EntityCruiser), Speed.ToString(), Weight.ToString(), MainColor.Name, AdditionalColor.Name, diff --git a/ProjectCruiser/Program.cs b/ProjectCruiser/Program.cs index faeb072..ecba91c 100644 --- a/ProjectCruiser/Program.cs +++ b/ProjectCruiser/Program.cs @@ -12,7 +12,6 @@ namespace ProjectCruiser // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); Application.Run(new ServiceForm2()); - // -> OceanForm1() inside* } } } \ No newline at end of file -- 2.25.1 From 7f58bbb1ad0dd00ac22543f9c391e2eb970e3871 Mon Sep 17 00:00:00 2001 From: DelphyAlmond Date: Sat, 15 Jun 2024 23:48:53 +0400 Subject: [PATCH 12/13] In process : solve log problem & add left exceptions --- .../CollectionGenericObj/ArrayGenObj.cs | 150 +++++++++++++----- .../CollectionGenericObj/ListGenObj.cs | 101 +++++++++--- .../CollectionGenericObj/StorageCollection.cs | 55 +++---- .../Exceptions/CollectionOverflowException.cs | 18 +++ .../Exceptions/ObjectNotFoundException.cs | 16 ++ .../PositionOutOfCollectionException.cs | 16 ++ ProjectCruiser/Program.cs | 29 +++- ProjectCruiser/ProjectCruiser.csproj | 10 ++ ProjectCruiser/ServiceForm2.cs | 62 ++++++-- ProjectCruiser/serilog.config | 13 ++ 10 files changed, 355 insertions(+), 115 deletions(-) create mode 100644 ProjectCruiser/Exceptions/CollectionOverflowException.cs create mode 100644 ProjectCruiser/Exceptions/ObjectNotFoundException.cs create mode 100644 ProjectCruiser/Exceptions/PositionOutOfCollectionException.cs create mode 100644 ProjectCruiser/serilog.config diff --git a/ProjectCruiser/CollectionGenericObj/ArrayGenObj.cs b/ProjectCruiser/CollectionGenericObj/ArrayGenObj.cs index 5c56167..cf2297a 100644 --- a/ProjectCruiser/CollectionGenericObj/ArrayGenObj.cs +++ b/ProjectCruiser/CollectionGenericObj/ArrayGenObj.cs @@ -1,4 +1,6 @@  +using ProjectCruiser.Exceptions; + namespace ProjectCruiser.CollectionGenericObj; public class ArrayGenObj : ICollectionGenObj @@ -36,74 +38,140 @@ public class ArrayGenObj : ICollectionGenObj // methods : public T? GetItem(int index) { - if (index > Count || index < 0) + try { + if (index > Count) + throw new CollectionOverflowException(index); + if (index < 0) + throw new PositionOutOfCollectionException(index); + + if (_collection[index] == null) + throw new ObjectNotFoundException(index); + + return _collection[index]; + } + catch (CollectionOverflowException ex) + { + Console.WriteLine(ex.Message); + return null; + } + catch (ObjectNotFoundException ex) + { + Console.WriteLine(ex.Message); + return null; + } + catch (PositionOutOfCollectionException ex) + { + Console.WriteLine(ex.Message); return null; } - return _collection[index]; } public int Insert(T? item) { - if (Count >= _maxCount || item == null) + if (item == null) { return -1; } + + try // выход за границы, курируется CollectionOverflowException { + if (Count >= _maxCount) + { + throw new CollectionOverflowException(Count); + } + + // any empty place -> fill immediately + for (int i = 0; i < _collection.Length; i++) + { + if (_collection[i] == null) + { + _collection[i] = item; + return i; + } + } + return Count; + } + catch (CollectionOverflowException ex) + { + Console.WriteLine(ex.Message); return -1; } - - // any empty place -> fill immediately - for (int i = 0; i < _collection.Length; i++) - { - if (_collection[i] == null) - { - _collection[i] = item; - return i; - } - } - return Count; } public int Insert(T? item, int index) { - if (index >= _maxCount || Count >= _maxCount || - index < 0 || _collection[index] != null - || item == null) + try { - return -1; - } + if (index < 0 || index >= _maxCount) throw new PositionOutOfCollectionException(index); + if (Count >= _maxCount) throw new CollectionOverflowException(Count); - if (_collection[index] == null) - { - _collection[index] = item; - return index; - } + if (item == null) throw new ObjectNotFoundException(index); - int min_diff = 100, firstNullIndex = 100; - - for (int i = 0; i < Count; i++) - { - if (_collection[i] == null - && min_diff > Math.Abs(index - i)) + if (_collection[index] == null) { - min_diff = Math.Abs(index - i); - firstNullIndex = i; + _collection[index] = item; + return index; + } + else + { + int min_diff = 100, firstNullIndex = 100; + + for (int i = 0; i < Count; i++) + { + if (_collection[i] == null && min_diff > Math.Abs(index - i)) + { + min_diff = Math.Abs(index - i); + firstNullIndex = i; + } + } + + _collection[firstNullIndex] = item; + return firstNullIndex; } } - - _collection[firstNullIndex] = item; - return firstNullIndex; + catch (CollectionOverflowException ex) + { + Console.WriteLine(ex.Message); + return -1; + } + catch (ObjectNotFoundException ex) + { + Console.WriteLine(ex.Message); + return -1; + } + catch (PositionOutOfCollectionException ex) + { + Console.WriteLine(ex.Message); + return -1; + } } public T? Remove(int index) { - if (index >= Count || index < 0) - // on the other positions items don't exist + try { + if (index >= _maxCount || index < 0) + // on the other positions items don't exist + { + throw new CollectionOverflowException(index); + // [?] PositionOutOfCollectionException <<< + } + + T? item = _collection[index]; + _collection[index] = null; + + if (item == null) throw new ObjectNotFoundException(index); + + return item; + } + catch (CollectionOverflowException ex) + { + Console.WriteLine(ex.Message); + return null; + } + catch (ObjectNotFoundException ex) + { + Console.WriteLine(ex.Message); return null; } - - T? item = _collection[index]; - _collection[index] = null; - return item; } public IEnumerable GetItems() diff --git a/ProjectCruiser/CollectionGenericObj/ListGenObj.cs b/ProjectCruiser/CollectionGenericObj/ListGenObj.cs index fd256d3..3e11e11 100644 --- a/ProjectCruiser/CollectionGenericObj/ListGenObj.cs +++ b/ProjectCruiser/CollectionGenericObj/ListGenObj.cs @@ -2,6 +2,7 @@ using System.Collections; using System.Collections.Generic; using System.Reflection; +using ProjectCruiser.Exceptions; namespace ProjectCruiser.CollectionGenericObj; @@ -40,49 +41,111 @@ public class ListGenObj : ICollectionGenObj public T? GetItem(int position) { - if (position >= Count || position < 0) + try { + if (position > Count) + throw new CollectionOverflowException(position); + if (position < 0) + throw new PositionOutOfCollectionException(position); + + if (_collection[position] == null) + throw new ObjectNotFoundException(position); + + return _collection[position]; + } + catch (CollectionOverflowException ex) + { + Console.WriteLine(ex.Message); + return null; + } + catch (ObjectNotFoundException ex) + { + Console.WriteLine(ex.Message); + return null; + } + catch (PositionOutOfCollectionException ex) + { + Console.WriteLine(ex.Message); return null; } - - return _collection[position]; } public int Insert(T? obj) { - if (Count >= _maxCount || obj == null) + if (obj == null) { return -1; } + + try // выход за границы, курируется CollectionOverflowException { + if (Count >= _maxCount) + { + throw new CollectionOverflowException(Count); + } + + _collection.Add(obj); + return Count; + } + catch (CollectionOverflowException ex) + { + Console.WriteLine(ex.Message); return -1; } - - _collection.Add(obj); - return Count; } public int Insert(T? obj, int position) { - if (position >= _maxCount || Count >= _maxCount || - position < 0 || _collection[position] != null - || obj == null) + try { + if (position < 0 || position >= _maxCount) throw new PositionOutOfCollectionException(position); + if (Count >= _maxCount) throw new CollectionOverflowException(Count); + + if (obj == null) throw new ObjectNotFoundException(position); + + _collection.Insert(position, obj); + return position; + } + catch (CollectionOverflowException ex) + { + Console.WriteLine(ex.Message); + return -1; + } + catch (ObjectNotFoundException ex) + { + Console.WriteLine(ex.Message); + return -1; + } + catch (PositionOutOfCollectionException ex) + { + Console.WriteLine(ex.Message); return -1; } - - _collection.Insert(position, obj); - return position; } public T? Remove(int position) { - if (position >= Count || position < 0) - // on the other positions items don't exist + try { + if (position >= _maxCount || position < 0) + // on the other positions items don't exist + { + throw new CollectionOverflowException(position); + } + + T? item = _collection[position]; + _collection.RemoveAt(position); + + if (item == null) throw new ObjectNotFoundException(position); + + return item; + } + catch (CollectionOverflowException ex) { + Console.WriteLine(ex.Message); + return null; + } + catch (ObjectNotFoundException ex) + { + Console.WriteLine(ex.Message); return null; } - - T? item = _collection[position]; - _collection.RemoveAt(position); - return item; } public IEnumerable GetItems() diff --git a/ProjectCruiser/CollectionGenericObj/StorageCollection.cs b/ProjectCruiser/CollectionGenericObj/StorageCollection.cs index 93ae0b4..a209124 100644 --- a/ProjectCruiser/CollectionGenericObj/StorageCollection.cs +++ b/ProjectCruiser/CollectionGenericObj/StorageCollection.cs @@ -1,5 +1,6 @@ using System.Text; using ProjectCruiser.DrawningSamples; +using ProjectCruiser.Exceptions; namespace ProjectCruiser.CollectionGenericObj; @@ -55,9 +56,11 @@ public class StorageCollection /// Путь и имя файла /// true - сохранение прошло успешно, /// false - ошибка при сохранении данных - public bool SaveData(string filename) + public void SaveData(string filename) { - if (_storages.Count == 0) { return false; } + if (_storages.Count == 0) + throw new NullReferenceException(" > No existing collections to save"); + if (File.Exists(filename)) { File.Delete(filename); } StringBuilder sb = new(); @@ -79,21 +82,6 @@ public class StorageCollection 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; @@ -107,7 +95,6 @@ public class StorageCollection using FileStream fs = new(filename, FileMode.Create); byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString()); fs.Write(info, 0, info.Length); - return true; } // Создание коллекции по типу @@ -122,12 +109,9 @@ public class StorageCollection } // Загрузка информации по кораблям в хранилище из файла - public bool LoadData(string filename) + public void LoadData(string filename) { - if (!File.Exists(filename)) - { - return false; - } + if (!File.Exists(filename)) throw new FileNotFoundException(); string bufferTextFromFile = ""; @@ -145,14 +129,9 @@ public class StorageCollection new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); if (strs == null || strs.Length == 0) - { - return false; - } + throw new NullReferenceException("> No data to decode"); if (!strs[0].Equals(_collectionKey)) - { - //если нет такой записи, то это не те данные - return false; - } + throw new InvalidDataException("> Incorrect data"); string[] companies = new string[strs.Length - 1]; for (int k = 1; k < strs.Length; k++) @@ -171,10 +150,9 @@ public class StorageCollection } CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); ICollectionGenObj? collection = StorageCollection.CreateCollection(collectionType); + if (collection == null) - { - return false; - } + throw new NullReferenceException("> Failed to create collection"); collection.MaxCount = Convert.ToInt32(record[2]); string[] set = record[3].Split(_separatorItems, @@ -184,15 +162,20 @@ public class StorageCollection { if (elem?.CreateDrawningCar() is T ship) { - if (collection.Insert(ship) == -1) + try { - return false; + if (collection.Insert(ship) == -1) + throw new IndexOutOfRangeException( + "> Failed to add to collection : " + record[3]); + } + catch (CollectionOverflowException e) + { + throw new CollectionOverflowException("Collection overflowed", e); } } } _storages.Add(record[0], collection); } - return true; } } diff --git a/ProjectCruiser/Exceptions/CollectionOverflowException.cs b/ProjectCruiser/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..43f991d --- /dev/null +++ b/ProjectCruiser/Exceptions/CollectionOverflowException.cs @@ -0,0 +1,18 @@ +using System.Runtime.Serialization; +namespace ProjectCruiser.Exceptions; + +// Класс, описывающий ошибку переполнения коллекции +[Serializable] +internal class CollectionOverflowException : ApplicationException +{ + public CollectionOverflowException(int count) + : base("Possible accsess of collection is over : " + count) { } + public CollectionOverflowException() : base() { } + public CollectionOverflowException(string message) : base(message) { } + public CollectionOverflowException(string message, Exception exception) : + base(message, exception) + { } + protected CollectionOverflowException(SerializationInfo info, + StreamingContext contex) : base(info, contex) { } +} + diff --git a/ProjectCruiser/Exceptions/ObjectNotFoundException.cs b/ProjectCruiser/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..81e29f9 --- /dev/null +++ b/ProjectCruiser/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,16 @@ +using System.Runtime.Serialization; +namespace ProjectCruiser.Exceptions; + +// Класс, описывающий ошибку, что по указанной позиции нет элемента +[Serializable] +internal class ObjectNotFoundException : ApplicationException +{ + public ObjectNotFoundException(int i) + : base("Didn't find obj on this position : " + i) { } + public ObjectNotFoundException() : base() { } + public ObjectNotFoundException(string message) : base(message) { } + public ObjectNotFoundException(string message, Exception exception) + : base(message, exception) { } + protected ObjectNotFoundException(SerializationInfo info, + StreamingContext contex) : base(info, contex) { } +} diff --git a/ProjectCruiser/Exceptions/PositionOutOfCollectionException.cs b/ProjectCruiser/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..266b7ee --- /dev/null +++ b/ProjectCruiser/Exceptions/PositionOutOfCollectionException.cs @@ -0,0 +1,16 @@ +using System.Runtime.Serialization; +namespace ProjectCruiser.Exceptions; + +// Класс, описывающий ошибку выхода за границы коллекции +[Serializable] +internal class PositionOutOfCollectionException : ApplicationException +{ + public PositionOutOfCollectionException(int i) + : base("Out of collection boarder. Position : " + i) { } + public PositionOutOfCollectionException() : base() { } + public PositionOutOfCollectionException(string message) : base(message) { } + public PositionOutOfCollectionException(string message, + Exception exception) : base(message, exception) { } + protected PositionOutOfCollectionException(SerializationInfo info, + StreamingContext contex) : base(info, contex) { } +} diff --git a/ProjectCruiser/Program.cs b/ProjectCruiser/Program.cs index ecba91c..7e7a369 100644 --- a/ProjectCruiser/Program.cs +++ b/ProjectCruiser/Program.cs @@ -1,17 +1,42 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; + namespace ProjectCruiser { internal static class Program { /// - /// The main entry point for the application. + /// The main entry point for the application. /// [STAThread] static void Main() { // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. + ApplicationConfiguration.Initialize(); - Application.Run(new ServiceForm2()); + ServiceCollection services = new(); + ConfigureServices(services); + + using ServiceProvider serviceProvider = services.BuildServiceProvider(); + Application.Run(serviceProvider.GetRequiredService()); + } + + /// DI + /// + private static void ConfigureServices(ServiceCollection services) + { + services.AddSingleton().AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + // [*] option.AddSerilog("serilog.config"); + option.AddSerilog("serilog.config"); + + // instead of : + // option.SetMinimumLevel(LogLevel.Information); + // option.AddNLog("nlog.config"); + }); } } } \ No newline at end of file diff --git a/ProjectCruiser/ProjectCruiser.csproj b/ProjectCruiser/ProjectCruiser.csproj index 663fdb8..1afe9e3 100644 --- a/ProjectCruiser/ProjectCruiser.csproj +++ b/ProjectCruiser/ProjectCruiser.csproj @@ -8,4 +8,14 @@ enable + + + + + + + Always + + + \ No newline at end of file diff --git a/ProjectCruiser/ServiceForm2.cs b/ProjectCruiser/ServiceForm2.cs index 3b0c05f..83edf3e 100644 --- a/ProjectCruiser/ServiceForm2.cs +++ b/ProjectCruiser/ServiceForm2.cs @@ -1,5 +1,9 @@ using ProjectCruiser.CollectionGenericObj; using ProjectCruiser.DrawningSamples; + +using Microsoft.Extensions.Logging; +// using NLog.Extensions.Logging; + namespace ProjectCruiser; public partial class ServiceForm2 : Form @@ -9,10 +13,16 @@ public partial class ServiceForm2 : Form private readonly StorageCollection _storageCollection; - public ServiceForm2() + // Логер + private readonly ILogger _logger; + + // Конструктор > logger + public ServiceForm2(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; + } // Выбор компании @@ -71,27 +81,39 @@ public partial class ServiceForm2 : Form // Передача объекта в другую форму private void btnChooseforTest_Click(object sender, EventArgs e) { + // Add EXCEPTIONS [!] if (_company == null) { return; } - DrawningBase? car = null; + DrawningBase? ship = null; int counter = 100; - while (car == null) + while (ship == null) { - car = _company.GetRandomObject(); - counter--; - if (counter <= 0) + try { - break; + ship = _company.GetRandomObject(); + counter--; + + if (counter <= 0) + { + break; + } } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + return; + } + } - if (car == null) + + if (ship == null) { return; } - OceanForm1 form = new() { SetShip = car }; + OceanForm1 form = new() { SetShip = ship }; form.ShowDialog(); } @@ -190,15 +212,17 @@ public partial class ServiceForm2 : Form { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.SaveData(saveFileDialog.FileName)) + try { + _storageCollection.SaveData(saveFileDialog.FileName); MessageBox.Show(" < Saved succesfully >", "Result :", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Saving to file : {filename}", saveFileDialog.FileName); } - else + catch (Exception ex) { - MessageBox.Show("< Failed to save >", "Result :", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message, "Result :", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("< Error > : {Message}", ex.Message); } } } @@ -208,16 +232,20 @@ public partial class ServiceForm2 : Form { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.LoadData(openFileDialog.FileName)) + try { + _storageCollection.LoadData(openFileDialog.FileName); MessageBox.Show(" < Loaded succesfully >", "Result :", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Loading from file : {filename}", openFileDialog.FileName); + RefreshListBoxItems(); } - else + catch (Exception ex) { - MessageBox.Show("< Failed to load >", "Result :", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("< Failed to load >" + ex.Message, + "Result :", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("< Error > : {Message}", ex.Message); } } } diff --git a/ProjectCruiser/serilog.config b/ProjectCruiser/serilog.config new file mode 100644 index 0000000..a00fcc6 --- /dev/null +++ b/ProjectCruiser/serilog.config @@ -0,0 +1,13 @@ + + + + + + + + + + + -- 2.25.1 From 507118762322d6568cadd14529075ecac9de956e Mon Sep 17 00:00:00 2001 From: DelphyAlmond Date: Sun, 16 Jun 2024 19:46:37 +0400 Subject: [PATCH 13/13] logging --- .../CollectionGenericObj/AbstractCompany.cs | 14 +- .../CollectionGenericObj/ArrayGenObj.cs | 179 +++++++----------- .../CollectionGenericObj/ListGenObj.cs | 121 +++--------- .../ShipSharingService.cs | 26 ++- .../CollectionGenericObj/StorageCollection.cs | 30 +-- .../Exceptions/CollectionOverflowException.cs | 2 +- .../Exceptions/ObjectNotFoundException.cs | 2 +- .../PositionOutOfCollectionException.cs | 2 +- ProjectCruiser/Program.cs | 23 ++- ProjectCruiser/ProjectCruiser.csproj | 14 +- ProjectCruiser/ServiceForm2.Designer.cs | 2 +- ProjectCruiser/ServiceForm2.cs | 90 ++++++--- ProjectCruiser/serilog.config | 13 -- ProjectCruiser/serilog.json | 15 ++ 14 files changed, 241 insertions(+), 292 deletions(-) delete mode 100644 ProjectCruiser/serilog.config create mode 100644 ProjectCruiser/serilog.json diff --git a/ProjectCruiser/CollectionGenericObj/AbstractCompany.cs b/ProjectCruiser/CollectionGenericObj/AbstractCompany.cs index 5b98774..fdd5d80 100644 --- a/ProjectCruiser/CollectionGenericObj/AbstractCompany.cs +++ b/ProjectCruiser/CollectionGenericObj/AbstractCompany.cs @@ -17,8 +17,8 @@ public abstract class AbstractCompany // Коллекция автомобилей protected ICollectionGenObj? _collection = null; - private int GetMaxCount => _pictureWidth * _pictureHeight / - (_placeSizeWidth * _placeSizeHeight); + private int GetMaxCount => (_pictureWidth / (_placeSizeWidth + 20)) + * ( _pictureHeight / (_placeSizeHeight + 4)); public AbstractCompany(int picWidth, int picHeight, ICollectionGenObj? collection) @@ -51,20 +51,22 @@ public abstract class AbstractCompany Bitmap bitmap = new(_pictureWidth, _pictureHeight); Graphics graphics = Graphics.FromImage(bitmap); DrawBackground(graphics); - SetObjectsPosition(); - for (int i = 0; i < (_collection?.Count ?? 0); ++i) + + SetObjectsPosition(_collection.Count - 1); + + for (int i = 0; i < (_collection?.Count ?? 0); i++) { DrawningBase? obj = _collection?.GetItem(i); obj?.DrawTransport(graphics); } + return bitmap; } - // Вывод заднего фона protected abstract void DrawBackground(Graphics g); // Расстановка объектов - protected abstract void SetObjectsPosition(); + protected abstract void SetObjectsPosition(int border); } diff --git a/ProjectCruiser/CollectionGenericObj/ArrayGenObj.cs b/ProjectCruiser/CollectionGenericObj/ArrayGenObj.cs index cf2297a..475640a 100644 --- a/ProjectCruiser/CollectionGenericObj/ArrayGenObj.cs +++ b/ProjectCruiser/CollectionGenericObj/ArrayGenObj.cs @@ -1,5 +1,4 @@ - -using ProjectCruiser.Exceptions; +using ProjectCruiser.Exceptions; namespace ProjectCruiser.CollectionGenericObj; @@ -11,7 +10,7 @@ public class ArrayGenObj : ICollectionGenObj // Максимально допустимое число объектов в массиве private int _maxCount; - public int Count => _collection.Count(s => s != null); + public int Count => _collection.Count(s => (s != null)); public int MaxCount { @@ -20,10 +19,10 @@ public class ArrayGenObj : ICollectionGenObj { if (value > 0) { + _maxCount = value; + if (_collection.Length == 0) _collection = new T?[value]; else Array.Resize(ref _collection, value); - - _maxCount = value; } } } @@ -38,140 +37,96 @@ public class ArrayGenObj : ICollectionGenObj // methods : public T? GetItem(int index) { - try - { - if (index > Count) - throw new CollectionOverflowException(index); - if (index < 0) - throw new PositionOutOfCollectionException(index); + if (index > _maxCount) + throw new CollectionOverflowException(index); + if (index < 0) + throw new PositionOutOfCollectionException(index); - if (_collection[index] == null) - throw new ObjectNotFoundException(index); + if (_collection[index] == null) + throw new ObjectNotFoundException(index); - return _collection[index]; - } - catch (CollectionOverflowException ex) - { - Console.WriteLine(ex.Message); - return null; - } - catch (ObjectNotFoundException ex) - { - Console.WriteLine(ex.Message); - return null; - } - catch (PositionOutOfCollectionException ex) - { - Console.WriteLine(ex.Message); - return null; - } + return _collection[index]; + + // CollectionOverflowException + // PositionOutOfCollectionException + // ObjectNotFoundException } public int Insert(T? item) { - if (item == null) { return -1; } + if (item == null) throw + new NullReferenceException("> Inserting item is null"); - try // выход за границы, курируется CollectionOverflowException - { - if (Count >= _maxCount) - { - throw new CollectionOverflowException(Count); - } + // выход за границы, курируется CollectionOverflowException + if (Count >= _maxCount) throw new CollectionOverflowException(Count); - // any empty place -> fill immediately - for (int i = 0; i < _collection.Length; i++) - { - if (_collection[i] == null) - { - _collection[i] = item; - return i; - } - } - return Count; - } - catch (CollectionOverflowException ex) + // any empty place -> fill immediately + for (int i = Count; i < _maxCount; i++) { - Console.WriteLine(ex.Message); - return -1; + if (_collection[i] == null) + { + _collection[i] = item; + return i; + } } + return Count; + + // NullReferenceException + // CollectionOverflowException } public int Insert(T? item, int index) { - try + if (index < 0 || index >= _maxCount) throw new PositionOutOfCollectionException(index); + if (Count >= _maxCount) throw new CollectionOverflowException(Count); + + if (item == null) throw + new NullReferenceException("> Inserting item (at position) is null"); + + if (_collection[index] == null) { - if (index < 0 || index >= _maxCount) throw new PositionOutOfCollectionException(index); - if (Count >= _maxCount) throw new CollectionOverflowException(Count); + _collection[index] = item; + return index; + } + else + { + int min_diff = 100, firstNullIndex = 100; - if (item == null) throw new ObjectNotFoundException(index); - - if (_collection[index] == null) + for (int i = 0; i < Count; i++) { - _collection[index] = item; - return index; - } - else - { - int min_diff = 100, firstNullIndex = 100; - - for (int i = 0; i < Count; i++) + if (_collection[i] == null && min_diff > Math.Abs(index - i)) { - if (_collection[i] == null && min_diff > Math.Abs(index - i)) - { - min_diff = Math.Abs(index - i); - firstNullIndex = i; - } + min_diff = Math.Abs(index - i); + firstNullIndex = i; } - - _collection[firstNullIndex] = item; - return firstNullIndex; } + + _collection[firstNullIndex] = item; + return firstNullIndex; } - catch (CollectionOverflowException ex) - { - Console.WriteLine(ex.Message); - return -1; - } - catch (ObjectNotFoundException ex) - { - Console.WriteLine(ex.Message); - return -1; - } - catch (PositionOutOfCollectionException ex) - { - Console.WriteLine(ex.Message); - return -1; - } + + // PositionOutOfCollectionException + // CollectionOverflowException + // NullReferenceException } public T? Remove(int index) { - try + if (index >= _maxCount || index < 0) + // on the other positions items don't exist { - if (index >= _maxCount || index < 0) - // on the other positions items don't exist - { - throw new CollectionOverflowException(index); - // [?] PositionOutOfCollectionException <<< - } - - T? item = _collection[index]; - _collection[index] = null; - - if (item == null) throw new ObjectNotFoundException(index); - - return item; - } - catch (CollectionOverflowException ex) - { - Console.WriteLine(ex.Message); - return null; - } - catch (ObjectNotFoundException ex) - { - Console.WriteLine(ex.Message); - return null; + throw new PositionOutOfCollectionException(index); } + + T? item = _collection[index]; + _collection[index] = null; + + if (item == null) throw new ObjectNotFoundException(index); + + return item; + + // PositionOutOfCollectionException + // ObjectNotFoundException } public IEnumerable GetItems() diff --git a/ProjectCruiser/CollectionGenericObj/ListGenObj.cs b/ProjectCruiser/CollectionGenericObj/ListGenObj.cs index 3e11e11..1cb23cf 100644 --- a/ProjectCruiser/CollectionGenericObj/ListGenObj.cs +++ b/ProjectCruiser/CollectionGenericObj/ListGenObj.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Reflection; -using ProjectCruiser.Exceptions; +using ProjectCruiser.Exceptions; namespace ProjectCruiser.CollectionGenericObj; @@ -41,111 +37,56 @@ public class ListGenObj : ICollectionGenObj public T? GetItem(int position) { - try - { - if (position > Count) - throw new CollectionOverflowException(position); - if (position < 0) - throw new PositionOutOfCollectionException(position); + if (position > _maxCount) + throw new CollectionOverflowException(position); + if (position < 0) + throw new PositionOutOfCollectionException(position); - if (_collection[position] == null) - throw new ObjectNotFoundException(position); + if (_collection[position] == null) + throw new ObjectNotFoundException(position); - return _collection[position]; - } - catch (CollectionOverflowException ex) - { - Console.WriteLine(ex.Message); - return null; - } - catch (ObjectNotFoundException ex) - { - Console.WriteLine(ex.Message); - return null; - } - catch (PositionOutOfCollectionException ex) - { - Console.WriteLine(ex.Message); - return null; - } + return _collection[position]; } public int Insert(T? obj) { - if (obj == null) { return -1; } + if (obj == null) + throw new NullReferenceException("> Inserting object is null"); - try // выход за границы, курируется CollectionOverflowException - { - if (Count >= _maxCount) - { - throw new CollectionOverflowException(Count); - } + // выход за границы, курируется CollectionOverflowException + if (Count >= _maxCount) throw new CollectionOverflowException(Count); - _collection.Add(obj); - return Count; - } - catch (CollectionOverflowException ex) - { - Console.WriteLine(ex.Message); - return -1; - } + _collection.Add(obj); + return Count; } public int Insert(T? obj, int position) { - try - { - if (position < 0 || position >= _maxCount) throw new PositionOutOfCollectionException(position); - if (Count >= _maxCount) throw new CollectionOverflowException(Count); + if (position < 0 || position >= _maxCount) + throw new PositionOutOfCollectionException(position); + if (Count >= _maxCount) throw new CollectionOverflowException(Count); - if (obj == null) throw new ObjectNotFoundException(position); + if (obj == null) + throw new NullReferenceException("> Inserting object (at position) is null"); - _collection.Insert(position, obj); - return position; - } - catch (CollectionOverflowException ex) - { - Console.WriteLine(ex.Message); - return -1; - } - catch (ObjectNotFoundException ex) - { - Console.WriteLine(ex.Message); - return -1; - } - catch (PositionOutOfCollectionException ex) - { - Console.WriteLine(ex.Message); - return -1; - } + _collection.Insert(position, obj); + return position; } public T? Remove(int position) { - try { - if (position >= _maxCount || position < 0) - // on the other positions items don't exist - { - throw new CollectionOverflowException(position); - } - - T? item = _collection[position]; - _collection.RemoveAt(position); - - if (item == null) throw new ObjectNotFoundException(position); - - return item; - } - catch (CollectionOverflowException ex) + if (position >= _maxCount || position < 0) + // on the other positions items don't exist { - Console.WriteLine(ex.Message); - return null; - } - catch (ObjectNotFoundException ex) - { - Console.WriteLine(ex.Message); - return null; + throw new PositionOutOfCollectionException(position); } + + T? item = _collection[position]; + _collection.RemoveAt(position); + + if (item == null) throw new ObjectNotFoundException(position); + + return item; } public IEnumerable GetItems() diff --git a/ProjectCruiser/CollectionGenericObj/ShipSharingService.cs b/ProjectCruiser/CollectionGenericObj/ShipSharingService.cs index e430deb..1fa2de7 100644 --- a/ProjectCruiser/CollectionGenericObj/ShipSharingService.cs +++ b/ProjectCruiser/CollectionGenericObj/ShipSharingService.cs @@ -41,27 +41,33 @@ public class ShipSharingService : AbstractCompany } } - protected override void SetObjectsPosition() + protected override void SetObjectsPosition(int border) { int index_collection = 0; - int newX = fromBorder + 6, newY = fromCeiling + 6; + int newY = fromCeiling + 4; if (_collection != null) { - for (int i = 0; i < MaxInColon; ++i) + for (int i = 0; i < MaxInColon; i++) { - newX = fromBorder + 2; - for (int j = 0; j < MaxInRow; ++j) + int newX = fromBorder + 2; + for (int j = 0; j < MaxInRow; j++) { - if (_collection.GetItem(index_collection) != null) + // TRY / CATCH [?] + _collection.GetItem(index_collection).SetPictureSize( + _pictureWidth, _pictureHeight); + + _collection.GetItem(index_collection).SetPosition(newX, newY); + + newX += _placeSizeWidth + between + 2; + + if (index_collection < border) { - _collection.GetItem(index_collection).SetPictureSize(_pictureWidth, _pictureHeight); - _collection.GetItem(index_collection).SetPosition(newX, newY); - newX += _placeSizeWidth + between + 2; index_collection++; } + else return; } - newY += _placeSizeHeight + 2; + newY += _placeSizeHeight + 1; } } } diff --git a/ProjectCruiser/CollectionGenericObj/StorageCollection.cs b/ProjectCruiser/CollectionGenericObj/StorageCollection.cs index a209124..acc8411 100644 --- a/ProjectCruiser/CollectionGenericObj/StorageCollection.cs +++ b/ProjectCruiser/CollectionGenericObj/StorageCollection.cs @@ -1,4 +1,5 @@ -using System.Text; +using System.Security.Cryptography; +using System.Text; using ProjectCruiser.DrawningSamples; using ProjectCruiser.Exceptions; @@ -32,7 +33,7 @@ public class StorageCollection if (name == null || _storages.ContainsKey(name) || collType == CollectionType.None) { - return; + throw new NullReferenceException("> Not enough information to save"); } ICollectionGenObj collection = CreateCollection(collType); @@ -43,7 +44,7 @@ public class StorageCollection public void DelCollection(string name) { if (_storages.ContainsKey(name)) _storages.Remove(name); - return; + else throw new NullReferenceException("> No such key in the list"); } // Доступ к коллекции ( по ключу-строке - её имени ) - индексатор [!!!] @@ -59,7 +60,7 @@ public class StorageCollection public void SaveData(string filename) { if (_storages.Count == 0) - throw new NullReferenceException(" > No existing collections to save"); + throw new NullReferenceException("> No existing collections to save"); if (File.Exists(filename)) { File.Delete(filename); } @@ -111,7 +112,7 @@ public class StorageCollection // Загрузка информации по кораблям в хранилище из файла public void LoadData(string filename) { - if (!File.Exists(filename)) throw new FileNotFoundException(); + if (!File.Exists(filename)) throw new FileNotFoundException("> No such file"); string bufferTextFromFile = ""; @@ -145,14 +146,13 @@ public class StorageCollection string[] record = data.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); if (record.Length != 4) // > // key | collType | maxcount | all next inf > 4 - { - continue; - } + { continue; } + CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); ICollectionGenObj? collection = StorageCollection.CreateCollection(collectionType); if (collection == null) - throw new NullReferenceException("> Failed to create collection"); + throw new NullReferenceException("[!] Failed to create collection"); collection.MaxCount = Convert.ToInt32(record[2]); string[] set = record[3].Split(_separatorItems, @@ -164,13 +164,15 @@ public class StorageCollection { try { - if (collection.Insert(ship) == -1) - throw new IndexOutOfRangeException( - "> Failed to add to collection : " + record[3]); + collection.Insert(ship); + + // throw new IndexOutOfRangeException IF IT WAS Insert(item, pos) + // NullReferenceException > + // CollectionOverflowException > } - catch (CollectionOverflowException e) + catch (Exception e) { - throw new CollectionOverflowException("Collection overflowed", e); + throw new Exception(e.Message); } } } diff --git a/ProjectCruiser/Exceptions/CollectionOverflowException.cs b/ProjectCruiser/Exceptions/CollectionOverflowException.cs index 43f991d..790d0a2 100644 --- a/ProjectCruiser/Exceptions/CollectionOverflowException.cs +++ b/ProjectCruiser/Exceptions/CollectionOverflowException.cs @@ -6,7 +6,7 @@ namespace ProjectCruiser.Exceptions; internal class CollectionOverflowException : ApplicationException { public CollectionOverflowException(int count) - : base("Possible accsess of collection is over : " + count) { } + : base("<> Possible accsess\nof collection is over : " + count) { } public CollectionOverflowException() : base() { } public CollectionOverflowException(string message) : base(message) { } public CollectionOverflowException(string message, Exception exception) : diff --git a/ProjectCruiser/Exceptions/ObjectNotFoundException.cs b/ProjectCruiser/Exceptions/ObjectNotFoundException.cs index 81e29f9..b6f8a4a 100644 --- a/ProjectCruiser/Exceptions/ObjectNotFoundException.cs +++ b/ProjectCruiser/Exceptions/ObjectNotFoundException.cs @@ -6,7 +6,7 @@ namespace ProjectCruiser.Exceptions; internal class ObjectNotFoundException : ApplicationException { public ObjectNotFoundException(int i) - : base("Didn't find obj on this position : " + i) { } + : base("<> Didn't find obj\non this position : " + i) { } public ObjectNotFoundException() : base() { } public ObjectNotFoundException(string message) : base(message) { } public ObjectNotFoundException(string message, Exception exception) diff --git a/ProjectCruiser/Exceptions/PositionOutOfCollectionException.cs b/ProjectCruiser/Exceptions/PositionOutOfCollectionException.cs index 266b7ee..305704e 100644 --- a/ProjectCruiser/Exceptions/PositionOutOfCollectionException.cs +++ b/ProjectCruiser/Exceptions/PositionOutOfCollectionException.cs @@ -6,7 +6,7 @@ namespace ProjectCruiser.Exceptions; internal class PositionOutOfCollectionException : ApplicationException { public PositionOutOfCollectionException(int i) - : base("Out of collection boarder. Position : " + i) { } + : base("<> Out of collection\nboarder. Position : " + i) { } public PositionOutOfCollectionException() : base() { } public PositionOutOfCollectionException(string message) : base(message) { } public PositionOutOfCollectionException(string message, diff --git a/ProjectCruiser/Program.cs b/ProjectCruiser/Program.cs index 7e7a369..9767135 100644 --- a/ProjectCruiser/Program.cs +++ b/ProjectCruiser/Program.cs @@ -1,5 +1,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Configuration; using Serilog; namespace ProjectCruiser @@ -16,26 +17,28 @@ namespace ProjectCruiser // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); + ServiceCollection services = new(); ConfigureServices(services); - using ServiceProvider serviceProvider = services.BuildServiceProvider(); Application.Run(serviceProvider.GetRequiredService()); - } - /// DI - /// + } private static void ConfigureServices(ServiceCollection services) { + string[] path = Directory.GetCurrentDirectory().Split('\\'); + string pathNeed = ""; + for (int i = 0; i < path.Length - 3; i++) + { + pathNeed += path[i] + "\\"; + } + services.AddSingleton().AddLogging(option => { option.SetMinimumLevel(LogLevel.Information); - // [*] option.AddSerilog("serilog.config"); - option.AddSerilog("serilog.config"); - - // instead of : - // option.SetMinimumLevel(LogLevel.Information); - // option.AddNLog("nlog.config"); + option.AddSerilog(new LoggerConfiguration().ReadFrom.Configuration( + new ConfigurationBuilder().AddJsonFile( + $"{pathNeed}serilog.json").Build()).CreateLogger()); }); } } diff --git a/ProjectCruiser/ProjectCruiser.csproj b/ProjectCruiser/ProjectCruiser.csproj index 1afe9e3..3d70e47 100644 --- a/ProjectCruiser/ProjectCruiser.csproj +++ b/ProjectCruiser/ProjectCruiser.csproj @@ -9,13 +9,15 @@ + + + + + + - - - - - Always - + + \ No newline at end of file diff --git a/ProjectCruiser/ServiceForm2.Designer.cs b/ProjectCruiser/ServiceForm2.Designer.cs index d065feb..dc4fd35 100644 --- a/ProjectCruiser/ServiceForm2.Designer.cs +++ b/ProjectCruiser/ServiceForm2.Designer.cs @@ -221,7 +221,7 @@ btnDelete.TabIndex = 4; btnDelete.Text = "Delete"; btnDelete.UseVisualStyleBackColor = true; - btnDelete.Click += btnRemoveCar_Click; + btnDelete.Click += btnRemoveShip_Click; // // btnAddCruiser // diff --git a/ProjectCruiser/ServiceForm2.cs b/ProjectCruiser/ServiceForm2.cs index 83edf3e..dfeae24 100644 --- a/ProjectCruiser/ServiceForm2.cs +++ b/ProjectCruiser/ServiceForm2.cs @@ -1,7 +1,7 @@ using ProjectCruiser.CollectionGenericObj; using ProjectCruiser.DrawningSamples; - using Microsoft.Extensions.Logging; +using ProjectCruiser.Exceptions; // using NLog.Extensions.Logging; namespace ProjectCruiser; @@ -22,7 +22,7 @@ public partial class ServiceForm2 : Form InitializeComponent(); _storageCollection = new(); _logger = logger; - + _logger.LogInformation("> Form is loaded successfully"); } // Выбор компании @@ -31,13 +31,10 @@ public partial class ServiceForm2 : Form toolPanel.Enabled = false; } - // Color picker (default : random) <...> - // Добавление корабля private void btnAddTransport_Click(object sender, EventArgs e) { EditorForm3 form3 = new(); - // TODO передать метод : form3.AddEvent(CreateObject); form3.Show(); } @@ -45,43 +42,58 @@ public partial class ServiceForm2 : Form // Создание объекта класса-перемещения private void CreateObject(DrawningBase? ship) { - if (_company == null || ship == null) - { - return; - } - if (_company + ship != -1) + try { + if (_company == null || ship == null) + { + throw new NullReferenceException(" > No existing collections to save"); + } + + int count = _company + ship; + MessageBox.Show("> Object was added"); pictureBox.Image = _company.Show(); + + _logger.LogInformation("> Adding object succeed {ship} at {count} position", ship, count); } - else + catch (Exception ex) { - MessageBox.Show("[!] Failed to add object"); + MessageBox.Show("[!] Failed to add object\n" + ex.Message); + _logger.LogError("< Error > : {Message}", ex.Message); } } // Удаление объекта - private void btnRemoveCar_Click(object sender, EventArgs e) + private void btnRemoveShip_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null) return; if (MessageBox.Show("[*] Remove object: Are you sure?", "Remove", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) return; + int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - if (_company - Convert.ToInt32(maskedTextBoxPosition.Text) != null) + try { - MessageBox.Show("> Object was removed"); - pictureBox.Image = _company.Show(); + if (_company - pos != null) + { + MessageBox.Show("> Object was removed"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Object at " + + pos + "position was deleted successfully"); + } + } + catch (Exception ex) + { + MessageBox.Show("[!] Failed to remove object"); + _logger.LogError("< Error > : {Message}", ex.Message); } - else MessageBox.Show("[!] Failed to remove object"); } // Передача объекта в другую форму private void btnChooseforTest_Click(object sender, EventArgs e) { - // Add EXCEPTIONS [!] if (_company == null) { return; @@ -117,7 +129,6 @@ public partial class ServiceForm2 : Form form.ShowDialog(); } - // Перерисовка коллекции private void btnRefresh_Click(object sender, EventArgs e) { if (_company == null) @@ -146,7 +157,17 @@ public partial class ServiceForm2 : Form collType = CollectionType.List; } - _storageCollection.AddCollection(maskedTxtBoxCName.Text, collType); + try + { + _storageCollection.AddCollection(maskedTxtBoxCName.Text, collType); + _logger.LogInformation("Adding collection succeed : {Name}, {Type}", maskedTxtBoxCName.Text, collType); + } + catch (NullReferenceException ex) + { + Console.WriteLine(ex.Message); + _logger.LogError("< Error > : {Message}", ex.Message); + } + RefreshListBoxItems(); } @@ -156,13 +177,21 @@ public partial class ServiceForm2 : Form { MessageBox.Show("Collection was not choosed"); return; - } - if (MessageBox.Show("Are you sure?", "Removing", MessageBoxButtons.OK, MessageBoxIcon.Question) != DialogResult.OK) + } if (MessageBox.Show("Are you sure?", "Removing", + MessageBoxButtons.OK, MessageBoxIcon.Question) + != DialogResult.OK) return; + + try { - return; + _storageCollection.DelCollection(listBox.SelectedItem.ToString()); + RefreshListBoxItems(); + _logger.LogInformation("Removing collection succeed : {Name}", listBox.SelectedItem.ToString); + } + catch (NullReferenceException ex) + { + Console.WriteLine(ex.Message); + _logger.LogError("< Error > : {Message}", ex.Message); } - _storageCollection.DelCollection(listBox.SelectedItem.ToString()); - RefreshListBoxItems(); } private void RefreshListBoxItems() @@ -199,7 +228,7 @@ public partial class ServiceForm2 : Form { case "Storage": _company = new ShipSharingService(pictureBox.Width, - pictureBox.Height, collection); + pictureBox.Height, collection); break; } @@ -235,9 +264,16 @@ public partial class ServiceForm2 : Form try { _storageCollection.LoadData(openFileDialog.FileName); + // LoadData() : Exceptions + // FileNotFoundException + // NullReferenceException + // InvalidDataException + // IndexOutOfRangeException + // CollectionOverflowException + MessageBox.Show(" < Loaded succesfully >", "Result :", MessageBoxButtons.OK, MessageBoxIcon.Information); - _logger.LogInformation("Loading from file : {filename}", openFileDialog.FileName); + _logger.LogInformation("Loading from file : {Filename}", openFileDialog.FileName); RefreshListBoxItems(); } diff --git a/ProjectCruiser/serilog.config b/ProjectCruiser/serilog.config deleted file mode 100644 index a00fcc6..0000000 --- a/ProjectCruiser/serilog.config +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - diff --git a/ProjectCruiser/serilog.json b/ProjectCruiser/serilog.json new file mode 100644 index 0000000..fd4d7d8 --- /dev/null +++ b/ProjectCruiser/serilog.json @@ -0,0 +1,15 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { "path": "log.log" } + } + ], + "Properties": { + "Application": "Sample" + } + } +} -- 2.25.1