1 Commits
lab7 ... laba3

Author SHA1 Message Date
Учебный
756f0c10b9 зафиксировать всё 2023-11-12 11:12:17 +04:00
41 changed files with 371 additions and 1828 deletions

View File

@@ -3,12 +3,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17 # Visual Studio Version 17
VisualStudioVersion = 17.7.34031.279 VisualStudioVersion = 17.7.34031.279
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ProjectBoat_bae", "ProjectBoat_bae\ProjectBoat_bae.csproj", "{D8469CDA-6475-44BF-BCDE-A69B80397FE3}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProjectBoat_bae", "ProjectBoat_bae\ProjectBoat_bae.csproj", "{D8469CDA-6475-44BF-BCDE-A69B80397FE3}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{9D03BD00-51B0-4389-84FD-8FF17153F0BE}"
ProjectSection(SolutionItems) = preProject
.editorconfig = .editorconfig
EndProjectSection
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution

View File

@@ -6,6 +6,7 @@ using System.Drawing;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using ProjectBoat_bae;
using ProjectBoat_bae.Entities; using ProjectBoat_bae.Entities;
using ProjectBoat_bae.MovementStrategy; using ProjectBoat_bae.MovementStrategy;
@@ -21,10 +22,10 @@ namespace ProjectBoat_bae.DrawningObjects
public EntityBoat? EntityBoat { get; protected set; } public EntityBoat? EntityBoat { get; protected set; }
// Ширина окна // Ширина окна
public int _pictureWidth; private int _pictureWidth;
// Высота окна // Высота окна
public int _pictureHeight; private int _pictureHeight;
// Левая координата прорисовки // Левая координата прорисовки
protected int _startPosX; protected int _startPosX;
@@ -33,10 +34,10 @@ namespace ProjectBoat_bae.DrawningObjects
protected int _startPosY; protected int _startPosY;
// Ширина прорисовки // Ширина прорисовки
protected readonly int _boatWidth = 70; protected readonly int _boatWidth = 80;
// Высота прорисовки // Высота прорисовки
protected readonly int _boatHeight = 40; protected readonly int _boatHeight = 50;
public int GetPosX => _startPosX; public int GetPosX => _startPosX;
public int GetPosY => _startPosY; public int GetPosY => _startPosY;
@@ -74,16 +75,8 @@ namespace ProjectBoat_bae.DrawningObjects
// Установка позиции // Установка позиции
public void SetPosition(int x, int y) public void SetPosition(int x, int y)
{ {
if (x < 0 || x + _boatWidth > _pictureWidth) _startPosX = Math.Min(x, _pictureWidth - _boatWidth);
{ _startPosY = Math.Min(y, _pictureHeight - _boatHeight);
x = Math.Max(0, _pictureWidth - _boatWidth);
}
if (y < 0 || y + _boatHeight > _pictureHeight)
{
y = Math.Max(0, _pictureHeight - _boatHeight);
}
_startPosX = x;
_startPosY = y;
} }
// Прорисовка объекта // Прорисовка объекта
@@ -96,17 +89,18 @@ namespace ProjectBoat_bae.DrawningObjects
Pen pen = new(Color.Black); Pen pen = new(Color.Black);
//корпус //корпус
Brush br = new SolidBrush(EntityBoat.BodyColor); Brush br = new SolidBrush(EntityBoat.BodyColor);
g.FillRectangle(br, _startPosX + 50, _startPosY + 85, 80, 50); g.FillRectangle(br, _startPosX + 20, _startPosY + 5, 70, 50);
//мотор //мотор
Brush brRed = new SolidBrush(EntityBoat.BodyColor); Brush brRed = new SolidBrush(EntityBoat.BodyColor);
g.FillEllipse(brRed, _startPosX + 30, _startPosY + 92, 35, 35); g.FillEllipse(brRed, _startPosX + 7, _startPosY + 12, 35, 35);
//стекла //стекла
Brush brBlue = new SolidBrush(Color.LightBlue); Brush brBlue = new SolidBrush(Color.LightBlue);
g.FillRectangle(brBlue, _startPosX + 125, _startPosY + 87, 5, 45); g.FillRectangle(brBlue, _startPosX + 70, _startPosY + 10, 5,
g.FillRectangle(brBlue, _startPosX + 75, _startPosY + 87, 55, 2); 40);
g.FillRectangle(brBlue, _startPosX + 75, _startPosY + 131, 55, 2); g.FillRectangle(brBlue, _startPosX + 35, _startPosY + 8, 35, 2);
g.FillRectangle(brBlue, _startPosX + 35, _startPosY + 51, 35, 2);
} }
// Проверка, что объект может переместится по указанному направлению // Проверка, что объект может переместится по указанному направлению
@@ -169,11 +163,5 @@ namespace ProjectBoat_bae.DrawningObjects
break; break;
} }
} }
public void ChangePictureSize(int width, int height)
{
_pictureWidth = width;
_pictureHeight = height;
}
} }
} }

View File

@@ -4,7 +4,6 @@ using System.ComponentModel;
using System.Data; using System.Data;
using System.Drawing; using System.Drawing;
using System.Linq; using System.Linq;
using System.Reflection;
using System.Text; using System.Text;
using ProjectBoat_bae.Entities; using ProjectBoat_bae.Entities;
@@ -32,26 +31,20 @@ namespace ProjectBoat_bae.DrawningObjects
{ {
return; return;
} }
Point[] points;
Pen pen = new(Color.Black); Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(Boat.AdditionalColor); Brush additionalBrush = new SolidBrush(Boat.AdditionalColor);
Brush brr = new SolidBrush(EntityBoat.BodyColor); Brush br = new SolidBrush(EntityBoat.BodyColor);
Brush brRed = new SolidBrush(EntityBoat.BodyColor);
Brush brBlue = new SolidBrush(Color.LightBlue);
if (Boat.Wing)
{
//вёсла
g.FillRectangle(additionalBrush, _startPosX + 55, _startPosY + 60, 5, 100);
g.FillRectangle(additionalBrush, _startPosX + 48, _startPosY + 60, 12, 8);
g.FillRectangle(additionalBrush, _startPosX + 48, _startPosY + 155, 12, 8);
}
base.DrawTransport(g);
//кресла
if (Boat.Body) if (Boat.Body)
{ {
g.FillRectangle(additionalBrush, _startPosX + 58, _startPosY + 90, 25, 40); //вёсла
g.FillRectangle(brRed, _startPosX + 35, _startPosY - 5, 5, 65);
g.FillRectangle(brRed, _startPosX + 28, _startPosY + 60, 12, 8);
g.FillRectangle(brRed, _startPosX + 28, _startPosY - 5, 12, 8);
} }
base.DrawTransport(g);
} }
} }
} }

View File

@@ -8,15 +8,11 @@ namespace ProjectBoat_bae.Entities
{ {
public class EntityBoat public class EntityBoat
{ {
public void SetBodyColor(Color color)
{
BodyColor = color;
}
public int Speed { get; private set; } public int Speed { get; private set; }
public double Weight { get; private set; } public double Weight { get; private set; }
public Color BodyColor { get; private set; } public Color BodyColor { get; private set; }
public double Step => (double)Speed * 200 / Weight; public double Step => (double)Speed * 100 / Weight;
public EntityBoat(int speed, double weight, Color bodyColor) public EntityBoat(int speed, double weight, Color bodyColor)
{ {

View File

@@ -8,11 +8,6 @@ namespace ProjectBoat_bae.Entities
{ {
public class EntityMotorBoat : EntityBoat public class EntityMotorBoat : EntityBoat
{ {
public void setAdditionalColor(Color color)
{
AdditionalColor = color;
}
public Color AdditionalColor { get; private set; } public Color AdditionalColor { get; private set; }
public bool Body { get; private set; } public bool Body { get; private set; }
public bool Wing { get; private set; } public bool Wing { get; private set; }

View File

@@ -29,7 +29,7 @@
private void InitializeComponent() private void InitializeComponent()
{ {
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormBoat)); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormBoat));
pictureBoxBoat = new PictureBox(); pictureBox1 = new PictureBox();
button_bottom = new Button(); button_bottom = new Button();
button_top = new Button(); button_top = new Button();
button_right = new Button(); button_right = new Button();
@@ -39,18 +39,18 @@
buttonStep = new Button(); buttonStep = new Button();
comboBoxStrategy = new ComboBox(); comboBoxStrategy = new ComboBox();
buttonSelectBoat_Click = new Button(); buttonSelectBoat_Click = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxBoat).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBox1).BeginInit();
SuspendLayout(); SuspendLayout();
// //
// pictureBoxBoat // pictureBox1
// //
pictureBoxBoat.Dock = DockStyle.Fill; pictureBox1.Dock = DockStyle.Fill;
pictureBoxBoat.Location = new Point(0, 0); pictureBox1.Location = new Point(0, 0);
pictureBoxBoat.Name = "pictureBoxBoat"; pictureBox1.Name = "pictureBox1";
pictureBoxBoat.Size = new Size(1178, 644); pictureBox1.Size = new Size(1178, 644);
pictureBoxBoat.SizeMode = PictureBoxSizeMode.AutoSize; pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBoxBoat.TabIndex = 0; pictureBox1.TabIndex = 0;
pictureBoxBoat.TabStop = false; pictureBox1.TabStop = false;
// //
// button_bottom // button_bottom
// //
@@ -153,7 +153,7 @@
buttonSelectBoat_Click.TabIndex = 10; buttonSelectBoat_Click.TabIndex = 10;
buttonSelectBoat_Click.Text = "Выбранная лодка"; buttonSelectBoat_Click.Text = "Выбранная лодка";
buttonSelectBoat_Click.UseVisualStyleBackColor = true; buttonSelectBoat_Click.UseVisualStyleBackColor = true;
buttonSelectBoat_Click.Click += buttonSelectBoat_Click_Click; buttonSelectBoat_Click.Click += this.buttonSelectBoat_Click_Click;
// //
// FormBoat // FormBoat
// //
@@ -169,17 +169,17 @@
Controls.Add(button_right); Controls.Add(button_right);
Controls.Add(button_top); Controls.Add(button_top);
Controls.Add(button_bottom); Controls.Add(button_bottom);
Controls.Add(pictureBoxBoat); Controls.Add(pictureBox1);
Name = "FormBoat"; Name = "FormBoat";
Text = "FormBoat"; Text = "Form1";
((System.ComponentModel.ISupportInitialize)pictureBoxBoat).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBox1).EndInit();
ResumeLayout(false); ResumeLayout(false);
PerformLayout(); PerformLayout();
} }
#endregion #endregion
private PictureBox pictureBoxBoat; private PictureBox pictureBox1;
private Button button_bottom; private Button button_bottom;
private Button button_top; private Button button_top;
private Button button_right; private Button button_right;

View File

@@ -37,11 +37,11 @@ namespace ProjectBoat_bae
{ {
return; return;
} }
Bitmap bmp = new(pictureBoxBoat.Width, Bitmap bmp = new(pictureBox1.Width,
pictureBoxBoat.Height); pictureBox1.Height);
Graphics gr = Graphics.FromImage(bmp); Graphics gr = Graphics.FromImage(bmp);
_drawingBoat.DrawTransport(gr); _drawingBoat.DrawTransport(gr);
pictureBoxBoat.Image = bmp; pictureBox1.Image = bmp;
} }
// Èçìåíåíèå ðàçìåðîâ ôîðìû // Èçìåíåíèå ðàçìåðîâ ôîðìû
@@ -90,7 +90,7 @@ namespace ProjectBoat_bae
_drawingBoat = new DrawningMotorBoat(random.Next(100, 300), _drawingBoat = new DrawningMotorBoat(random.Next(100, 300),
random.Next(1000, 3000), color, dopColor, Convert.ToBoolean(random.Next(0, 2)), random.Next(1000, 3000), color, dopColor, Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)),
pictureBoxBoat.Width, pictureBoxBoat.Height); pictureBox1.Width, pictureBox1.Height);
_drawingBoat.SetPosition(random.Next(10, 100), random.Next(10, 100)); _drawingBoat.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw(); Draw();
} }
@@ -103,7 +103,7 @@ namespace ProjectBoat_bae
{ {
color = dialog.Color; color = dialog.Color;
} }
_drawingBoat = new Drawningboat(random.Next(100, 300), random.Next(1000, 3000), color, pictureBoxBoat.Width, pictureBoxBoat.Height); _drawingBoat = new Drawningboat(random.Next(100, 300), random.Next(1000, 3000), color, pictureBox1.Width, pictureBox1.Height);
_drawingBoat.SetPosition(random.Next(10, 100), random.Next(10, 100)); _drawingBoat.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw(); Draw();
} }
@@ -127,7 +127,7 @@ namespace ProjectBoat_bae
{ {
return; return;
} }
_abstractStrategy.SetData(new DrawningObjectBoat(_drawingBoat), pictureBoxBoat.Width, pictureBoxBoat.Height); _abstractStrategy.SetData(new DrawningObjectBoat(_drawingBoat), pictureBox1.Width, pictureBox1.Height);
comboBoxStrategy.Enabled = false; comboBoxStrategy.Enabled = false;
} }
if (_abstractStrategy == null) if (_abstractStrategy == null)

View File

@@ -0,0 +1,124 @@
namespace ProjectBoat_bae
{
partial class FormBoatCollection
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
pictureBoxCollection = new PictureBox();
buttonAddBoat_Click = new Button();
buttonRemoveBoat_Click = new Button();
buttonRefreshCollection_Click = new Button();
textBox1 = new TextBox();
maskedTextBoxNumber = new MaskedTextBox();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
SuspendLayout();
//
// pictureBoxCollection
//
pictureBoxCollection.Location = new Point(0, 0);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(1176, 647);
pictureBoxCollection.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBoxCollection.TabIndex = 0;
pictureBoxCollection.TabStop = false;
//
// buttonAddBoat_Click
//
buttonAddBoat_Click.Location = new Point(955, 73);
buttonAddBoat_Click.Name = "buttonAddBoat_Click";
buttonAddBoat_Click.Size = new Size(201, 47);
buttonAddBoat_Click.TabIndex = 1;
buttonAddBoat_Click.Text = "Добавить лодку";
buttonAddBoat_Click.UseVisualStyleBackColor = true;
buttonAddBoat_Click.Click += buttonAddBoat_Click_Click;
//
// buttonRemoveBoat_Click
//
buttonRemoveBoat_Click.Location = new Point(955, 345);
buttonRemoveBoat_Click.Name = "buttonRemoveBoat_Click";
buttonRemoveBoat_Click.Size = new Size(201, 46);
buttonRemoveBoat_Click.TabIndex = 2;
buttonRemoveBoat_Click.Text = "Удалить лодку";
buttonRemoveBoat_Click.UseVisualStyleBackColor = true;
buttonRemoveBoat_Click.Click += buttonRemoveBoat_Click_Click;
//
// buttonRefreshCollection_Click
//
buttonRefreshCollection_Click.Location = new Point(955, 421);
buttonRefreshCollection_Click.Name = "buttonRefreshCollection_Click";
buttonRefreshCollection_Click.Size = new Size(201, 50);
buttonRefreshCollection_Click.TabIndex = 3;
buttonRefreshCollection_Click.Text = "Обновить коллекцию";
buttonRefreshCollection_Click.UseVisualStyleBackColor = true;
buttonRefreshCollection_Click.Click += buttonRefreshCollection_Click_Click;
//
// textBox1
//
textBox1.BackColor = SystemColors.MenuBar;
textBox1.Location = new Point(955, 12);
textBox1.Name = "textBox1";
textBox1.Size = new Size(150, 31);
textBox1.TabIndex = 4;
textBox1.Text = "Инструменты";
textBox1.TextAlign = HorizontalAlignment.Center;
//
// maskedTextBoxNumber
//
maskedTextBoxNumber.Location = new Point(979, 293);
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(150, 31);
maskedTextBoxNumber.TabIndex = 5;
maskedTextBoxNumber.Text = "_";
//
// FormBoatCollection
//
AutoScaleDimensions = new SizeF(10F, 25F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1178, 644);
Controls.Add(maskedTextBoxNumber);
Controls.Add(textBox1);
Controls.Add(buttonRefreshCollection_Click);
Controls.Add(buttonRemoveBoat_Click);
Controls.Add(buttonAddBoat_Click);
Controls.Add(pictureBoxCollection);
Name = "FormBoatCollection";
Text = "FormBoatCollection";
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private PictureBox pictureBoxCollection;
private Button buttonAddBoat_Click;
private Button buttonRemoveBoat_Click;
private Button buttonRefreshCollection_Click;
private TextBox textBox1;
private MaskedTextBox maskedTextBoxNumber;
}
}

View File

@@ -0,0 +1,76 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ProjectBoat_bae.DrawningObjects;
using ProjectBoat_bae.Generics;
using ProjectBoat_bae.MovementStrategy;
namespace ProjectBoat_bae
{
public partial class FormBoatCollection : Form
{
private readonly BoatsGenericCollection<Drawningboat, DrawningObjectBoat> _boats;
public FormBoatCollection()
{
InitializeComponent();
_boats = new BoatsGenericCollection<Drawningboat, DrawningObjectBoat>(pictureBoxCollection.Width, pictureBoxCollection.Height);
}
// Добавление объекта в набор
private void buttonAddBoat_Click_Click(object sender, EventArgs e)
{
FormBoat form = new();
if (form.ShowDialog() == DialogResult.OK)
{
if (_boats + form.SelectedBoat != -1)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = _boats.ShowBoats();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
}
// Удаление объекта из набора
private void buttonRemoveBoat_Click_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = -1;
try
{
pos = Convert.ToInt32(maskedTextBoxNumber.Text);
}
catch (Exception ex) { }
if (_boats - pos)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = _boats.ShowBoats();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
private void buttonRefreshCollection_Click_Click(object sender, EventArgs e)
{
pictureBoxCollection.Image = _boats.ShowBoats();
}
}
}

View File

@@ -20,10 +20,10 @@ namespace ProjectBoat_bae.Generics
/// <summary> /// <summary>
/// Размер занимаемого объектом места (ширина) /// Размер занимаемого объектом места (ширина)
/// </summary> /// </summary>
private readonly int _placeSizeWidth = 200; private readonly int _placeSizeWidth = 160;
// Размер занимаемого объектом места (высота) // Размер занимаемого объектом места (высота)
private readonly int _placeSizeHeight = 200; private readonly int _placeSizeHeight = 160;
// Набор объектов // Набор объектов
private readonly SetGeneric<T> _collection; private readonly SetGeneric<T> _collection;
@@ -39,31 +39,32 @@ namespace ProjectBoat_bae.Generics
} }
// Перегрузка оператора сложения // Перегрузка оператора сложения
public static bool operator +(BoatsGenericCollection<T, U> collect, T obj) public static int operator +(BoatsGenericCollection<T, U> collect, T?
obj)
{ {
if (obj == null) if (obj == null)
{ {
return false; return -1;
} }
return (bool)collect._collection.Insert(obj); return collect._collection.Insert(obj);
} }
// Перегрузка оператора вычитания // Перегрузка оператора вычитания
public static T? operator -(BoatsGenericCollection<T, U> collect, int public static bool operator -(BoatsGenericCollection<T, U> collect, int
pos) pos)
{ {
T? obj = collect._collection[pos]; T? obj = collect._collection.Get(pos);
if (obj != null) if (obj != null)
{ {
collect._collection.Remove(pos); collect._collection.Remove(pos);
} }
return obj; return false;
} }
// Получение объекта IMoveableObject // Получение объекта IMoveableObject
public U? GetU(int pos) public U? GetU(int pos)
{ {
return (U?)_collection[pos]?.GetMoveableObject; return (U?)_collection.Get(pos)?.GetMoveableObject;
} }
// Вывод всего набора объектов // Вывод всего набора объектов
@@ -99,17 +100,15 @@ namespace ProjectBoat_bae.Generics
{ {
for (int i = 0; i < _collection.Count; i++) for (int i = 0; i < _collection.Count; i++)
{ {
T? t = _collection[i]; Drawningboat boat = _collection.Get(i);
if (t != null)
if (boat != null)
{ {
t.SetPosition((i % (_pictureWidth / _placeSizeWidth)) * _placeSizeWidth, (i / (_pictureWidth / _placeSizeWidth)) * _placeSizeHeight); int width = _pictureWidth / _placeSizeWidth;
if (t is Drawningboat) (t as Drawningboat).DrawTransport(g); boat.SetPosition(i % width * _placeSizeWidth, (i / (_pictureWidth / _placeSizeWidth)) * _placeSizeHeight);
else t.DrawTransport(g); boat.DrawTransport(g);
} }
} }
} }
// Получение объектов коллекции
public IEnumerable<T?> GetBoats => _collection.GetBoats();
} }
} }

View File

@@ -0,0 +1,66 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBoat_bae.Generics
{
internal class SetGeneric<T> where T : class
{
private readonly T?[] _places;
public int Count => _places.Length;
public SetGeneric(int count)
{
_places = new T?[count];
}
public int Insert(T boat)
{
if (_places[Count - 1] != null)
return -1;
return Insert(boat, 0);
}
public int Insert(T boat, int position)
{
if (position < 0 || position >= Count)
return -1;
if (_places[position] != null)
{
int indexEnd = position + 1;
while (_places[indexEnd] != null)
{
indexEnd++;
}
for (int i = indexEnd + 1; i > position; i--)
{
_places[i] = _places[i - 1];
}
}
_places[position] = boat;
return position;
}
public bool Remove(int position)
{
if (position < 0 || position >= _places.Count())
return false;
_places[position] = null;
return true;
}
public T? Get(int position)
{
if (position < 0 || position >= _places.Count())
return null;
return _places[position];
}
}
}

View File

@@ -0,0 +1,17 @@
namespace ProjectBoat_bae
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[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 FormBoatCollection());
}
}
}

View File

@@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
</Project>

View File

@@ -1,121 +0,0 @@
[*.cs]
# IDE0005: Директива using не нужна.
dotnet_diagnostic.IDE0005.severity = silent
csharp_style_throw_expression = true:suggestion
[*.{cs,vb}]
dotnet_style_operator_placement_when_wrapping = beginning_of_line
tab_width = 4
indent_size = 4
dotnet_style_coalesce_expression = true:suggestion
dotnet_style_null_propagation = true:suggestion
dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion
dotnet_style_prefer_auto_properties = true:silent
dotnet_style_object_initializer = true:suggestion
dotnet_style_prefer_collection_expression = true:suggestion
dotnet_style_collection_initializer = true:suggestion
dotnet_style_prefer_simplified_boolean_expressions = true:suggestion
dotnet_style_prefer_conditional_expression_over_assignment = true:silent
dotnet_style_prefer_conditional_expression_over_return = true:silent
dotnet_style_explicit_tuple_names = true:suggestion
dotnet_style_prefer_inferred_tuple_names = true:suggestion
dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion
dotnet_style_prefer_compound_assignment = true:suggestion
dotnet_style_prefer_simplified_interpolation = true:suggestion
dotnet_style_namespace_match_folder = true:suggestion
[*.cs]
#### Стили именования ####
# Правила именования
dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion
dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface
dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i
dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.types_should_be_pascal_case.symbols = types
dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case
dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members
dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case
# Спецификации символов
dotnet_naming_symbols.interface.applicable_kinds = interface
dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.interface.required_modifiers =
dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum
dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.types.required_modifiers =
dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method
dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.non_field_members.required_modifiers =
# Стили именования
dotnet_naming_style.begins_with_i.required_prefix = I
dotnet_naming_style.begins_with_i.required_suffix =
dotnet_naming_style.begins_with_i.word_separator =
dotnet_naming_style.begins_with_i.capitalization = pascal_case
dotnet_naming_style.pascal_case.required_prefix =
dotnet_naming_style.pascal_case.required_suffix =
dotnet_naming_style.pascal_case.word_separator =
dotnet_naming_style.pascal_case.capitalization = pascal_case
dotnet_naming_style.pascal_case.required_prefix =
dotnet_naming_style.pascal_case.required_suffix =
dotnet_naming_style.pascal_case.word_separator =
dotnet_naming_style.pascal_case.capitalization = pascal_case
[*.vb]
#### Стили именования ####
# Правила именования
dotnet_naming_rule.interface_should_be_начинается_с_i.severity = suggestion
dotnet_naming_rule.interface_should_be_начинается_с_i.symbols = interface
dotnet_naming_rule.interface_should_be_начинается_с_i.style = начинается_с_i
dotnet_naming_rule.типы_should_be_всечастиспрописнойбуквы.severity = suggestion
dotnet_naming_rule.типы_should_be_всечастиспрописнойбуквы.symbols = типы
dotnet_naming_rule.типы_should_be_всечастиспрописнойбуквы.style = всечастиспрописнойбуквы
dotnet_naming_rule.не_являющиеся_полем_члены_should_be_всечастиспрописнойбуквы.severity = suggestion
dotnet_naming_rule.не_являющиеся_полем_члены_should_be_всечастиспрописнойбуквы.symbols = не_являющиеся_полем_члены
dotnet_naming_rule.не_являющиеся_полем_члены_should_be_всечастиспрописнойбуквы.style = всечастиспрописнойбуквы
# Спецификации символов
dotnet_naming_symbols.interface.applicable_kinds = interface
dotnet_naming_symbols.interface.applicable_accessibilities = public, friend, private, protected, protected_friend, private_protected
dotnet_naming_symbols.interface.required_modifiers =
dotnet_naming_symbols.типы.applicable_kinds = class, struct, interface, enum
dotnet_naming_symbols.типы.applicable_accessibilities = public, friend, private, protected, protected_friend, private_protected
dotnet_naming_symbols.типы.required_modifiers =
dotnet_naming_symbols.не_являющиеся_полем_члены.applicable_kinds = property, event, method
dotnet_naming_symbols.не_являющиеся_полем_члены.applicable_accessibilities = public, friend, private, protected, protected_friend, private_protected
dotnet_naming_symbols.не_являющиеся_полем_члены.required_modifiers =
# Стили именования
dotnet_naming_style.начинается_с_i.required_prefix = I
dotnet_naming_style.начинается_с_i.required_suffix =
dotnet_naming_style.начинается_с_i.word_separator =
dotnet_naming_style.начинается_с_i.capitalization = pascal_case
dotnet_naming_style.всечастиспрописнойбуквы.required_prefix =
dotnet_naming_style.всечастиспрописнойбуквы.required_suffix =
dotnet_naming_style.всечастиспрописнойбуквы.word_separator =
dotnet_naming_style.всечастиспрописнойбуквы.capitalization = pascal_case
dotnet_naming_style.всечастиспрописнойбуквы.required_prefix =
dotnet_naming_style.всечастиспрописнойбуквы.required_suffix =
dotnet_naming_style.всечастиспрописнойбуквы.word_separator =
dotnet_naming_style.всечастиспрописнойбуквы.capitalization = pascal_case

View File

@@ -1,33 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBoat_bae.Exceptions
{
[Serializable]
internal class BoatNotFoundException : ApplicationException
{
public BoatNotFoundException(int i)
: base($"Не найден объект по позиции {i}")
{ }
public BoatNotFoundException()
: base()
{ }
public BoatNotFoundException(string Message)
: base(Message)
{ }
public BoatNotFoundException(string Message, Exception Exception)
: base(Message, Exception)
{ }
public BoatNotFoundException(SerializationInfo Info, StreamingContext Context)
: base(Info, Context)
{ }
}
}

View File

@@ -1,33 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBoat_bae.Exceptions
{
[Serializable]
internal class StorageOverflowException : ApplicationException
{
public StorageOverflowException(int Count)
: base($"В наборе превышено допустимое количество {Count}")
{ }
public StorageOverflowException()
: base()
{ }
public StorageOverflowException(string Message)
: base(Message)
{ }
public StorageOverflowException(string Message, Exception Exception)
: base(Message, Exception)
{ }
public StorageOverflowException(SerializationInfo Info, StreamingContext Context)
: base(Info, Context)
{ }
}
}

View File

@@ -1,53 +0,0 @@
using System;
using System.Collections.Generic;
using System.Drawing.Text;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectBoat_bae.DrawningObjects;
using ProjectBoat_bae.Entities;
namespace ProjectBoat_bae
{
internal static class ExtentionBoat
{
// Разделитель для записи информации по объекту в файл
private static readonly char _separatorForObject = ':';
// Создание объекта из строки
public static Drawningboat? CreateDrawningBoat(this string info, char _separatorForObject, int _pictureWidth, int _pictureHeight)
{
string[] strs = info.Split(_separatorForObject);
if (strs.Length == 3)
{
return new Drawningboat(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), _pictureWidth, _pictureHeight);
}
if (strs.Length == 7)
{
return new DrawningMotorBoat(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]),
Color.FromName(strs[3]), Convert.ToBoolean(strs[4]),
Convert.ToBoolean(strs[5]), _pictureWidth, _pictureHeight);
}
return null;
}
// Получение данных для сохранения в файл
public static string GetDataForSave(this Drawningboat drawningBoat, char _separatorForObject)
{
var boat = drawningBoat.EntityBoat;
var str =
$"{boat.Speed}{_separatorForObject}{boat.Weight}{_separatorForObject}{boat.BodyColor.Name}";
if (boat is not EntityMotorBoat motorBoat)
{
return str;
}
return
$"{str}{_separatorForObject}{motorBoat.AdditionalColor.Name}{_separatorForObject}{motorBoat.Body}{_separatorForObject}{motorBoat.Wing}{_separatorForObject}";
}
}
}

View File

@@ -1,220 +0,0 @@
namespace ProjectBoat_bae
{
partial class FormBoatCollection
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
pictureBoxCollection = new PictureBox();
listBoxStorages = new ListBox();
ButtonAddObject = new Button();
textBoxStorageName = new TextBox();
ButtonDelObject = new Button();
ButtonAddBoat = new Button();
ButtonRemoveBoat = new Button();
ButtonRefreshCollection = new Button();
textBoxBoat = new TextBox();
menuStrip1 = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
SaveToolStripMenuItem = new ToolStripMenuItem();
LoadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
menuStrip1.SuspendLayout();
SuspendLayout();
//
// pictureBoxCollection
//
pictureBoxCollection.Location = new Point(0, 0);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(784, 647);
pictureBoxCollection.TabIndex = 0;
pictureBoxCollection.TabStop = false;
//
// listBoxStorages
//
listBoxStorages.FormattingEnabled = true;
listBoxStorages.ItemHeight = 25;
listBoxStorages.Location = new Point(935, 146);
listBoxStorages.Name = "listBoxStorages";
listBoxStorages.Size = new Size(231, 129);
listBoxStorages.TabIndex = 1;
listBoxStorages.SelectedIndexChanged += listBoxStorages_SelectedIndexChanged;
//
// ButtonAddObject
//
ButtonAddObject.BackColor = SystemColors.ButtonHighlight;
ButtonAddObject.Location = new Point(935, 102);
ButtonAddObject.Name = "ButtonAddObject";
ButtonAddObject.Size = new Size(231, 38);
ButtonAddObject.TabIndex = 2;
ButtonAddObject.Text = "Добавить в набор";
ButtonAddObject.UseVisualStyleBackColor = false;
ButtonAddObject.Click += ButtonAddObject_Click_1;
//
// textBoxStorageName
//
textBoxStorageName.Location = new Point(935, 65);
textBoxStorageName.Name = "textBoxStorageName";
textBoxStorageName.Size = new Size(231, 31);
textBoxStorageName.TabIndex = 3;
//
// ButtonDelObject
//
ButtonDelObject.BackColor = SystemColors.ButtonHighlight;
ButtonDelObject.Location = new Point(935, 281);
ButtonDelObject.Name = "ButtonDelObject";
ButtonDelObject.Size = new Size(231, 34);
ButtonDelObject.TabIndex = 4;
ButtonDelObject.Text = "Удалить набор";
ButtonDelObject.UseVisualStyleBackColor = false;
ButtonDelObject.Click += ButtonDelObject_Click;
//
// ButtonAddBoat
//
ButtonAddBoat.BackColor = SystemColors.ButtonHighlight;
ButtonAddBoat.Location = new Point(935, 401);
ButtonAddBoat.Name = "ButtonAddBoat";
ButtonAddBoat.Size = new Size(231, 34);
ButtonAddBoat.TabIndex = 5;
ButtonAddBoat.Text = "Добавить лодку";
ButtonAddBoat.UseVisualStyleBackColor = false;
ButtonAddBoat.Click += ButtonAddBoat_Click;
//
// ButtonRemoveBoat
//
ButtonRemoveBoat.BackColor = SystemColors.ButtonHighlight;
ButtonRemoveBoat.Location = new Point(935, 479);
ButtonRemoveBoat.Name = "ButtonRemoveBoat";
ButtonRemoveBoat.Size = new Size(231, 34);
ButtonRemoveBoat.TabIndex = 6;
ButtonRemoveBoat.Text = "Удалить лодку";
ButtonRemoveBoat.UseVisualStyleBackColor = false;
ButtonRemoveBoat.Click += ButtonRemoveBoat_Click;
//
// ButtonRefreshCollection
//
ButtonRefreshCollection.BackColor = SystemColors.ButtonHighlight;
ButtonRefreshCollection.Location = new Point(935, 575);
ButtonRefreshCollection.Name = "ButtonRefreshCollection";
ButtonRefreshCollection.Size = new Size(231, 34);
ButtonRefreshCollection.TabIndex = 7;
ButtonRefreshCollection.Text = "Обновить коллекцию";
ButtonRefreshCollection.UseVisualStyleBackColor = false;
ButtonRefreshCollection.Click += ButtonRefreshCollection_Click;
//
// textBoxBoat
//
textBoxBoat.Location = new Point(958, 441);
textBoxBoat.Name = "textBoxBoat";
textBoxBoat.Size = new Size(173, 31);
textBoxBoat.TabIndex = 8;
//
// menuStrip1
//
menuStrip1.ImageScalingSize = new Size(24, 24);
menuStrip1.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new Size(1178, 33);
menuStrip1.TabIndex = 9;
menuStrip1.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { SaveToolStripMenuItem, LoadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(69, 29);
файлToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
SaveToolStripMenuItem.Size = new Size(270, 34);
SaveToolStripMenuItem.Text = "Сохранение";
SaveToolStripMenuItem.Click += SaveToolStripMenu_Click;
//
// LoadToolStripMenuItem
//
LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
LoadToolStripMenuItem.Size = new Size(270, 34);
LoadToolStripMenuItem.Text = "Загрузка";
LoadToolStripMenuItem.Click += LoadToolStripMenu_Click;
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog1";
openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// FormBoatCollection
//
AutoScaleDimensions = new SizeF(10F, 25F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1178, 644);
Controls.Add(menuStrip1);
Controls.Add(textBoxBoat);
Controls.Add(ButtonRefreshCollection);
Controls.Add(ButtonRemoveBoat);
Controls.Add(ButtonAddBoat);
Controls.Add(ButtonDelObject);
Controls.Add(textBoxStorageName);
Controls.Add(ButtonAddObject);
Controls.Add(listBoxStorages);
Controls.Add(pictureBoxCollection);
MainMenuStrip = menuStrip1;
Name = "FormBoatCollection";
Text = "FormBoatCollection";
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
private PictureBox pictureBoxCollection;
private ListBox listBoxStorages;
private Button ButtonAddObject;
private TextBox textBoxStorageName;
private Button ButtonDelObject;
private Button ButtonAddBoat;
private Button ButtonRemoveBoat;
private Button ButtonRefreshCollection;
private TextBox textBoxBoat;
private MenuStrip menuStrip1;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
}
}

View File

@@ -1,233 +0,0 @@
using Microsoft.Extensions.Logging;
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 ProjectBoat_bae.DrawningObjects;
using ProjectBoat_bae.Generics;
using ProjectBoat_bae.Exceptions;
using ProjectBoat_bae.MovementStrategy;
using NLog;
namespace ProjectBoat_bae
{
public partial class FormBoatCollection : Form
{
// Набор объектов
private readonly BoatsGenericStorage _storage;
// Логер
private readonly
Microsoft.Extensions.Logging.ILogger? _logger;
public FormBoatCollection(ILogger<FormBoatCollection> logger)
{
InitializeComponent();
_storage = new BoatsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
}
// Заполнение listBoxObjects
private void ReloadObjects()
{
int index = listBoxStorages.SelectedIndex;
listBoxStorages.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++)
{
listBoxStorages.Items.Add(_storage.Keys[i]);
}
if (listBoxStorages.Items.Count > 0 && (index == -1 || index
>= listBoxStorages.Items.Count))
{
listBoxStorages.SelectedIndex = 0;
}
else if (listBoxStorages.Items.Count > 0 && index > -1 &&
index < listBoxStorages.Items.Count)
{
listBoxStorages.SelectedIndex = index;
}
}
// Добавление набора в коллекцию
private void ButtonAddObject_Click_1(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxStorageName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
_logger.LogInformation($"Added set: {textBoxStorageName.Text}");
}
// Удаление набора
private void ButtonDelObject_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
if (string.IsNullOrEmpty(textBoxStorageName.Text))
{
MessageBox.Show("Не всё заполнено", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Неудачная попытка. Коллекция не добавлена, не все данные заполнены");
return;
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
}
// Добавление объекта в набор
private void ButtonAddBoat_Click(object sender, EventArgs e)
{
FormBoatConfig formPlaneConfig = new FormBoatConfig();
formPlaneConfig.AddEvent(AddBoat);
formPlaneConfig.Show();
}
private void AddBoat(Drawningboat boat)
{
boat._pictureWidth = pictureBoxCollection.Width;
boat._pictureHeight = pictureBoxCollection.Height;
if (listBoxStorages.SelectedIndex == -1) return;
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null) return;
if (obj + boat)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowBoats();
_logger.LogInformation($"Добавлен объект {obj}");
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
//удаление объекта
private void ButtonRemoveBoat_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удалить", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
try
{
int pos = Convert.ToInt32(textBoxBoat.Text);
if (obj - pos != null)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowBoats();
_logger.LogInformation($"лодка удалена из набора {listBoxStorages.SelectedItem.ToString()}");
}
else
{
MessageBox.Show("Объект не удален");
_logger.LogWarning($"лодка не удалена из набора {listBoxStorages.SelectedItem.ToString()}");
}
}
catch (BoatNotFoundException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"BoatNotFound: {ex.Message} in set {listBoxStorages.SelectedItem.ToString()}");
}
catch (Exception ex)
{
MessageBox.Show("Объекта нет");
_logger.LogWarning("Not input");
}
}
// Обновление
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
pictureBoxCollection.Image = obj.ShowBoats();
}
//Выбор набора
private void listBoxStorages_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBoxCollection.Image =
_storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowBoats();
}
//сохранение
private void SaveToolStripMenu_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogWarning($"Файл {saveFileDialog.FileName} успешно сохранен");
}
catch (Exception ex)
{
_logger.LogWarning("Не удалось сохранить");
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
//загрузка
private void LoadToolStripMenu_Click(object sender, EventArgs args)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.LoadData(openFileDialog.FileName);
_logger.LogInformation($"Данные загружены из файла {openFileDialog.FileName}");
ReloadObjects();
}
catch (Exception ex)
{
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogWarning($"Не удалось загрузить информацию из файла: {ex.Message}");
}
}
}
}
}

View File

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

View File

@@ -1,373 +0,0 @@
namespace ProjectBoat_bae
{
partial class FormBoatConfig
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
pictureBoxObject = new PictureBox();
groupBoxBoat = new GroupBox();
checkBoxBoat2 = new CheckBox();
labelModifiedObject = new Label();
labelSimpleObject = new Label();
groupBoxColors = new GroupBox();
panelPurple = new Panel();
panelGray = new Panel();
panelWhite = new Panel();
panelBlack = new Panel();
panelYellow = new Panel();
panelBlue = new Panel();
panelGreen = new Panel();
panelRed = new Panel();
numericUpDownSpeed = new NumericUpDown();
numericUpDownWeight = new NumericUpDown();
Speed = new Label();
checkBoxBoat = new CheckBox();
Weight = new Label();
pictureBox1 = new PictureBox();
PanelObject = new Panel();
LabelAdditionalColor = new Label();
LabelColor = new Label();
buttonOk = new Button();
buttonCancel = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
groupBoxBoat.SuspendLayout();
groupBoxColors.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)pictureBox1).BeginInit();
PanelObject.SuspendLayout();
SuspendLayout();
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(38, 30);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(388, 328);
pictureBoxObject.TabIndex = 0;
pictureBoxObject.TabStop = false;
//
// groupBoxBoat
//
groupBoxBoat.Controls.Add(checkBoxBoat2);
groupBoxBoat.Controls.Add(labelModifiedObject);
groupBoxBoat.Controls.Add(labelSimpleObject);
groupBoxBoat.Controls.Add(groupBoxColors);
groupBoxBoat.Controls.Add(numericUpDownSpeed);
groupBoxBoat.Controls.Add(numericUpDownWeight);
groupBoxBoat.Controls.Add(Speed);
groupBoxBoat.Controls.Add(checkBoxBoat);
groupBoxBoat.Controls.Add(Weight);
groupBoxBoat.Controls.Add(pictureBox1);
groupBoxBoat.Location = new Point(12, 12);
groupBoxBoat.Name = "groupBoxBoat";
groupBoxBoat.Size = new Size(668, 449);
groupBoxBoat.TabIndex = 1;
groupBoxBoat.TabStop = false;
groupBoxBoat.Text = "Параметры";
//
// checkBoxBoat2
//
checkBoxBoat2.AutoSize = true;
checkBoxBoat2.Location = new Point(21, 227);
checkBoxBoat2.Name = "checkBoxBoat2";
checkBoxBoat2.Size = new Size(230, 29);
checkBoxBoat2.TabIndex = 12;
checkBoxBoat2.Text = "Признак наличия вёсел";
checkBoxBoat2.UseVisualStyleBackColor = true;
//
// labelModifiedObject
//
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.Location = new Point(464, 227);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(138, 38);
labelModifiedObject.TabIndex = 11;
labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
labelModifiedObject.MouseDown += LabelObject_MouseDown;
//
// labelSimpleObject
//
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Location = new Point(334, 227);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(124, 38);
labelSimpleObject.TabIndex = 10;
labelSimpleObject.Text = "Простой";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
labelSimpleObject.MouseDown += LabelObject_MouseDown;
//
// groupBoxColors
//
groupBoxColors.Controls.Add(panelPurple);
groupBoxColors.Controls.Add(panelGray);
groupBoxColors.Controls.Add(panelWhite);
groupBoxColors.Controls.Add(panelBlack);
groupBoxColors.Controls.Add(panelYellow);
groupBoxColors.Controls.Add(panelBlue);
groupBoxColors.Controls.Add(panelGreen);
groupBoxColors.Controls.Add(panelRed);
groupBoxColors.Location = new Point(334, 30);
groupBoxColors.Name = "groupBoxColors";
groupBoxColors.Size = new Size(268, 175);
groupBoxColors.TabIndex = 9;
groupBoxColors.TabStop = false;
groupBoxColors.Text = "Цвета";
//
// panelPurple
//
panelPurple.BackColor = Color.FromArgb(192, 0, 192);
panelPurple.Location = new Point(205, 109);
panelPurple.Name = "panelPurple";
panelPurple.Size = new Size(45, 45);
panelPurple.TabIndex = 11;
//
// panelGray
//
panelGray.BackColor = Color.Gray;
panelGray.Location = new Point(144, 109);
panelGray.Name = "panelGray";
panelGray.Size = new Size(45, 45);
panelGray.TabIndex = 11;
//
// panelWhite
//
panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(79, 109);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(45, 45);
panelWhite.TabIndex = 11;
//
// panelBlack
//
panelBlack.BackColor = Color.Black;
panelBlack.Location = new Point(17, 109);
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(45, 45);
panelBlack.TabIndex = 11;
//
// panelYellow
//
panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(205, 45);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(45, 45);
panelYellow.TabIndex = 11;
//
// panelBlue
//
panelBlue.BackColor = Color.Navy;
panelBlue.Location = new Point(144, 45);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(45, 45);
panelBlue.TabIndex = 11;
//
// panelGreen
//
panelGreen.BackColor = Color.FromArgb(0, 64, 0);
panelGreen.Location = new Point(79, 45);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(45, 45);
panelGreen.TabIndex = 11;
//
// panelRed
//
panelRed.AllowDrop = true;
panelRed.BackColor = Color.FromArgb(192, 0, 0);
panelRed.Location = new Point(17, 45);
panelRed.Name = "panelRed";
panelRed.Size = new Size(45, 45);
panelRed.TabIndex = 10;
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(148, 61);
numericUpDownSpeed.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownSpeed.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownSpeed.Name = "numericUpDownSpeed";
numericUpDownSpeed.Size = new Size(90, 31);
numericUpDownSpeed.TabIndex = 4;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(148, 104);
numericUpDownWeight.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownWeight.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownWeight.Name = "numericUpDownWeight";
numericUpDownWeight.Size = new Size(90, 31);
numericUpDownWeight.TabIndex = 5;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// Speed
//
Speed.AutoSize = true;
Speed.Location = new Point(21, 61);
Speed.Name = "Speed";
Speed.Size = new Size(89, 25);
Speed.TabIndex = 2;
Speed.Text = "Скорость";
//
// checkBoxBoat
//
checkBoxBoat.AutoSize = true;
checkBoxBoat.Location = new Point(21, 176);
checkBoxBoat.Name = "checkBoxBoat";
checkBoxBoat.Size = new Size(240, 29);
checkBoxBoat.TabIndex = 6;
checkBoxBoat.Text = "Признак наличия кресел";
checkBoxBoat.UseVisualStyleBackColor = true;
//
// Weight
//
Weight.AutoSize = true;
Weight.Location = new Point(21, 104);
Weight.Name = "Weight";
Weight.Size = new Size(39, 25);
Weight.TabIndex = 3;
Weight.Text = "Вес";
//
// pictureBox1
//
pictureBox1.Location = new Point(0, 0);
pictureBox1.Name = "pictureBox1";
pictureBox1.Size = new Size(668, 449);
pictureBox1.TabIndex = 2;
pictureBox1.TabStop = false;
//
// PanelObject
//
PanelObject.AllowDrop = true;
PanelObject.BorderStyle = BorderStyle.FixedSingle;
PanelObject.Controls.Add(LabelAdditionalColor);
PanelObject.Controls.Add(LabelColor);
PanelObject.Controls.Add(pictureBoxObject);
PanelObject.Location = new Point(696, 23);
PanelObject.Name = "PanelObject";
PanelObject.Size = new Size(460, 378);
PanelObject.TabIndex = 2;
PanelObject.DragDrop += PanelObject_DragDrop;
PanelObject.DragEnter += PanelObject_DragEnter;
PanelObject.MouseDown += PanelColor_MouseDown;
//
// LabelAdditionalColor
//
LabelAdditionalColor.AllowDrop = true;
LabelAdditionalColor.AutoSize = true;
LabelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
LabelAdditionalColor.Location = new Point(333, 0);
LabelAdditionalColor.Name = "LabelAdditionalColor";
LabelAdditionalColor.Size = new Size(93, 27);
LabelAdditionalColor.TabIndex = 1;
LabelAdditionalColor.Text = "Доп. цвет";
LabelAdditionalColor.DragDrop += LabelAdditionalColor_DragDrop;
LabelAdditionalColor.DragEnter += LabelAdditionalColor_DragEnter;
//
// LabelColor
//
LabelColor.AllowDrop = true;
LabelColor.AutoSize = true;
LabelColor.BorderStyle = BorderStyle.FixedSingle;
LabelColor.Location = new Point(38, 0);
LabelColor.Name = "LabelColor";
LabelColor.Size = new Size(53, 27);
LabelColor.TabIndex = 0;
LabelColor.Text = "Цвет";
LabelColor.DragDrop += LabelColor_DragDrop;
LabelColor.DragEnter += LabelColor_DragEnter;
//
// buttonOk
//
buttonOk.Location = new Point(696, 418);
buttonOk.Name = "buttonOk";
buttonOk.Size = new Size(216, 43);
buttonOk.TabIndex = 0;
buttonOk.Text = "Добавить";
buttonOk.UseVisualStyleBackColor = true;
buttonOk.Click += buttonOk_Click_1;
//
// buttonCancel
//
buttonCancel.Location = new Point(940, 418);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(216, 43);
buttonCancel.TabIndex = 3;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
//
// FormBoatConfig
//
AutoScaleDimensions = new SizeF(10F, 25F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1178, 498);
Controls.Add(buttonCancel);
Controls.Add(buttonOk);
Controls.Add(PanelObject);
Controls.Add(groupBoxBoat);
Name = "FormBoatConfig";
Text = "FormBoatConfig";
((System.ComponentModel.ISupportInitialize)pictureBoxObject).EndInit();
groupBoxBoat.ResumeLayout(false);
groupBoxBoat.PerformLayout();
groupBoxColors.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).EndInit();
((System.ComponentModel.ISupportInitialize)pictureBox1).EndInit();
PanelObject.ResumeLayout(false);
PanelObject.PerformLayout();
ResumeLayout(false);
}
#endregion
private PictureBox pictureBoxObject;
private GroupBox groupBoxBoat;
private Label Speed;
private Label Weight;
private NumericUpDown numericUpDownSpeed;
private NumericUpDown numericUpDownWeight;
private GroupBox groupBoxColors;
private CheckBox checkBoxBoat;
private Label labelSimpleObject;
private Panel panelPurple;
private Panel panelGray;
private Panel panelWhite;
private Panel panelBlack;
private Panel panelYellow;
private Panel panelBlue;
private Panel panelGreen;
private Panel panelRed;
private Label labelModifiedObject;
private Panel PanelObject;
private Button buttonOk;
private Button buttonCancel;
private Label LabelAdditionalColor;
private Label LabelColor;
private PictureBox pictureBox1;
private CheckBox checkBoxBoat2;
}
}

View File

@@ -1,168 +0,0 @@
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 ProjectBoat_bae.DrawningObjects;
using ProjectBoat_bae.Entities;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace ProjectBoat_bae
{
public partial class FormBoatConfig : Form
{
// Переменная-выбранная лодка
public Drawningboat? _boat = null;
// Событие
private event Action<Drawningboat>? EventAddBoat;
// Добавление события
public void AddEvent(Action<Drawningboat> ev)
{
if (EventAddBoat == null)
{
EventAddBoat = ev;
}
else
{
EventAddBoat += ev;
}
}
// Конструктор
public FormBoatConfig()
{
InitializeComponent();
panelBlack.MouseDown += PanelColor_MouseDown;
panelPurple.MouseDown += PanelColor_MouseDown;
panelGray.MouseDown += PanelColor_MouseDown;
panelGreen.MouseDown += PanelColor_MouseDown;
panelRed.MouseDown += PanelColor_MouseDown;
panelWhite.MouseDown += PanelColor_MouseDown;
panelYellow.MouseDown += PanelColor_MouseDown;
panelBlue.MouseDown += PanelColor_MouseDown;
labelSimpleObject.MouseDown += LabelObject_MouseDown;
labelModifiedObject.MouseDown += LabelObject_MouseDown;
buttonCancel.Click += (s, e) => Close();
}
// Метод прорисовки
private void DrawBoat()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_boat?.SetPosition(5, 5);
_boat?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
// Передаем информацию при нажатии на Label
private void LabelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label)?.DoDragDrop((sender as Label)?.Name, 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)
{
ILogger<FormBoatCollection> logger = new NullLogger<FormBoatCollection>();
switch (e.Data?.GetData(DataFormats.Text).ToString())
{
case "labelSimpleObject":
_boat = new Drawningboat((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value, Color.White, pictureBoxObject.Width, pictureBoxObject.Height);
break;
case "labelModifiedObject":
_boat = new DrawningMotorBoat((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value, Color.White, Color.Black, checkBoxBoat.Checked, checkBoxBoat2.Checked, pictureBoxObject.Width, pictureBoxObject.Height);
break;
}
DrawBoat();
}
// Отправляем цвет с панели
private void PanelColor_MouseDown(object sender, MouseEventArgs e)
{
(sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor,
DragDropEffects.Move | DragDropEffects.Copy);
}
private void LabelColor_DragDrop(object sender, DragEventArgs e)
{
if (_boat == null)
return;
switch (((Label)sender).Name)
{
case "LabelColor":
_boat?.EntityBoat?.SetBodyColor((Color)e.Data.GetData(typeof(Color)));
break;
case "LabelAdditionalColor":
if (!(_boat is ProjectBoat_bae))
return;
(_boat.EntityBoat as EntityMotorBoat)?.setAdditionalColor(color:
(Color)e.Data.GetData(typeof(Color)));
break;
}
DrawBoat();
}
private void LabelColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(typeof(Color)) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void LabelAdditionalColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)) && _boat != null && _boat is Drawningboat)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void LabelAdditionalColor_DragDrop(object sender, DragEventArgs e)
{
var color = (Color)e.Data.GetData(typeof(Color));
//Приведение к EntityTrolleybus для замены доп. цвета
EntityMotorBoat? _motorboat = _boat.EntityBoat as EntityMotorBoat;
_motorboat.setAdditionalColor(color);
DrawBoat();
}
private void buttonOk_Click_1(object sender, EventArgs e)
{
EventAddBoat?.Invoke(_boat);
Close();
}
}
}

View File

@@ -1,148 +0,0 @@
using System;
using System.Collections.Generic;
using System.DirectoryServices.ActiveDirectory;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectBoat_bae.DrawningObjects;
using ProjectBoat_bae.MovementStrategy;
using ProjectBoat_bae.Entities;
using ProjectBoat_bae.Exceptions;
namespace ProjectBoat_bae.Generics
{
internal class BoatsGenericStorage
{
readonly Dictionary<string, BoatsGenericCollection<Drawningboat, DrawningObjectBoat>> _boatStorages;
public List<string> Keys => _boatStorages.Keys.ToList();
private readonly int _pictureWidth;
private readonly int _pictureHeight;
public BoatsGenericStorage(int pictureWidth, int pictureHeight)
{
_boatStorages = new Dictionary<string, BoatsGenericCollection<Drawningboat, DrawningObjectBoat>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
public void AddSet(string name)
{
if (_boatStorages.ContainsKey(name)) return;
_boatStorages[name] = new BoatsGenericCollection<Drawningboat, DrawningObjectBoat>(_pictureWidth, _pictureHeight);
}
public void DelSet(string name)
{
if (!_boatStorages.ContainsKey(name)) return;
_boatStorages.Remove(name);
}
public BoatsGenericCollection<Drawningboat, DrawningObjectBoat>?
this[string ind]
{
get
{
if (_boatStorages.ContainsKey(ind)) return _boatStorages[ind];
return null;
}
}
private static readonly char _separatorForKeyValue = '|';
private readonly char _separatorRecords = ';';
private static readonly char _separatorForObject = ':';
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string,
BoatsGenericCollection<Drawningboat, DrawningObjectBoat>> record in _boatStorages)
{
StringBuilder records = new();
foreach (Drawningboat? elem in record.Value.GetBoats)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
throw new Exception("Невалидная операция, нет данных для сохранения");
}
using FileStream fs = new(filename, FileMode.Create);
byte[] info = new
UTF8Encoding(true).GetBytes($"BoatStorage{Environment.NewLine}{data}");
fs.Write(info, 0, info.Length);
return;
}
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не найден");
}
using (StreamReader fs = File.OpenText(filename))
{
string str = fs.ReadLine();
if (str == null || str.Length == 0)
{
throw new ArgumentException("Нет объекта для добавления");
}
if (str.StartsWith("BoatsStorage"))
{
throw new InvalidDataException("Неверный формат данных");
}
_boatStorages.Clear();
string strs = "";
while ((strs = fs.ReadLine()) != null)
{
if (strs == null)
{
return;
}
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
continue;
}
BoatsGenericCollection<Drawningboat, DrawningObjectBoat> collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
Drawningboat? boat = elem?.CreateDrawningBoat(_separatorForObject, _pictureWidth, _pictureHeight);
if (boat != null)
{
if (!(collection + boat))
{
try
{
_ = collection + boat;
}
catch (BoatNotFoundException e)
{
throw e;
}
catch (StorageOverflowException e)
{
throw e;
}
}
}
}
_boatStorages.Add(record[0], collection);
}
}
}
}
}

View File

@@ -1,77 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBoat_bae.Generics
{
internal class SetGeneric<T> where T : class
{
private readonly List<T?> _places;
public int Count => _places.Count;
// Максимальное количество объектов в списке
private readonly int _maxCount;
// Конструктор
public SetGeneric(int count)
{
_maxCount = count;
_places = new List<T?>(_maxCount);
}
public bool Insert(T boat)
{
return Insert(boat, 0);
}
public bool Insert(T boat, int position)
{
if (position < 0 || position >= _maxCount)
return false;
if (Count >= _maxCount)
return false;
_places.Insert(0, boat);
return true;
}
public bool Remove(int position)
{
if (position < 0 || position > _maxCount)
return false;
if (position >= Count)
return false;
_places.RemoveAt(position);
return true;
}
public T? this[int position]
{
get
{
if (position < 0 || position > _maxCount)
return null;
return _places[position];
}
set
{
if (position < 0 || position > _maxCount)
return;
_places[position] = value;
}
}
public IEnumerable<T?> GetBoats(int? maxBoats = null)
{
for (int i = 0; i < _places.Count; ++i)
{
yield return _places[i];
if (maxBoats.HasValue && i == maxBoats.Value)
{
yield break;
}
}
}
}
}

View File

@@ -1,53 +0,0 @@
//using NLog;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.VisualBasic.ApplicationServices;
using NLog.Extensions.Logging;
using Serilog;
namespace ProjectBoat_bae
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run((serviceProvider.GetRequiredService<FormBoatCollection>()));
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormBoatCollection>().AddLogging(option =>
{
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
//используется для создания исходных текстов конфигурации для приложени
//SetBasePath Задает базовый путь для файла конфигурации к текущему каталогу приложения.
// файл JSON в качестве источника конфигурации.
var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile(path: $"{pathNeed}appsettings.json", optional: false, reloadOnChange: true).Build();
//настроить формат записи логов
//используется для настройки регистратора Serilog.
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

View File

@@ -1,54 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<None Remove="appSettings.json" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.5" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Resource Include="appSettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Resource>
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="nlog.config.xml">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@@ -1,20 +0,0 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "log_.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "Boats"
}
}
}

View File

@@ -1,14 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true" internalLogLevel="Info">
<targets>
<target xsi:type="File" name="tofile" fileName="boatlog-
${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>