5 Commits
lab4 ... lab8

Author SHA1 Message Date
Efi
ed57ab5202 Лабораторная работа 8 2023-12-26 23:38:54 +04:00
Efi
7c2ac102e0 Лабораторная работа 7 2023-12-26 19:28:29 +04:00
Efi
f52af0e723 Лабораторная работа 6 2023-12-26 16:16:22 +04:00
Efi
970ee90862 Changes: AddSet check 2023-12-22 12:03:14 +04:00
Efi
ecb55016e8 Лабораторная работа 5 2023-12-21 22:40:01 +04:00
23 changed files with 1357 additions and 70 deletions

View File

@@ -8,6 +8,21 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="DependencyInjection.AutoRegistration" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" 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="Microsoft.Extensions.Logging.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.7" />
<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.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
@@ -23,4 +38,8 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<Folder Include="Logs\" />
</ItemGroup>
</Project>

View File

@@ -122,6 +122,14 @@ namespace AirBomber.DrawingObjects
}
public void setAddColor(Color color)
{
if (EntityWarAirplane is EntityAirBomber airBomber)
{
airBomber.setAddColor(color);
}
}
}
}

View File

@@ -233,5 +233,9 @@ namespace AirBomber.DrawingObjects
}
public void setColor(Color color)
{
EntityWarAirplane.setColor(color);
}
}
}

View File

@@ -0,0 +1,60 @@
using AirBomber.DrawingObjects;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AirBomber.Entities;
namespace AirBomber.Generics
{
internal class DrawingWarAirplaneEqutables : IEqualityComparer<DrawingWarAirplane?>
{
public bool Equals(DrawingWarAirplane? x, DrawingWarAirplane? y)
{
if (x == null || x.EntityWarAirplane == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityWarAirplane == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityWarAirplane.Speed != y.EntityWarAirplane.Speed)
{
return false;
}
if (x.EntityWarAirplane.Weight != y.EntityWarAirplane.Weight)
{
return false;
}
if (x.EntityWarAirplane.BodyColor != y.EntityWarAirplane.BodyColor)
{
return false;
}
if (x is DrawingAirBomber && y is DrawingAirBomber)
{
EntityAirBomber EntityX = (EntityAirBomber)x.EntityWarAirplane;
EntityAirBomber EntityY = (EntityAirBomber)y.EntityWarAirplane;
if (EntityX.FuelTank != EntityY.FuelTank)
return false;
if (EntityX.Bombs != EntityY.Bombs)
return false;
if (EntityX.Bombs && EntityX.FuelTank != EntityY.FuelTank && EntityY.Bombs)
return false;
if (EntityX.AdditionalColor != EntityY.AdditionalColor)
return false;
}
return true;
}
public int GetHashCode([DisallowNull] DrawingWarAirplane obj)
{
return obj.GetHashCode();
}
}
}

View File

@@ -15,5 +15,9 @@ namespace AirBomber.Entities
FuelTank = fuelTank;
Bombs = bombs;
}
public void setAddColor(Color color)
{
AdditionalColor = color;
}
}
}

View File

@@ -18,5 +18,10 @@ namespace AirBomber.Entities
Weight = weight;
BodyColor = bodyColor;
}
public void setColor(Color color)
{
BodyColor = color;
}
}
}

View File

@@ -0,0 +1,46 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AirBomber.Entities;
namespace AirBomber.DrawingObjects
{
public static class ExtentionDrawingWarAirplane
{
public static DrawingWarAirplane? CreateDrawingWarAirplane(this string info, char separatorForObject,
int width, int height)
{
string[] strs = info.Split(separatorForObject);
if(strs.Length == 3)
{
return new DrawingWarAirplane(Convert.ToInt32(strs[0]), Convert.ToInt32(strs[1]),
Color.FromName(strs[2]), width, height);
}
if(strs.Length == 6)
{
return new DrawingAirBomber(Convert.ToInt32(strs[0]), Convert.ToInt32(strs[1]),
Color.FromName(strs[2]), Color.FromName(strs[3]), Convert.ToBoolean(strs[4]),
Convert.ToBoolean(strs[5]), width, height);
}
return null;
}
public static string GetDataForSave(this DrawingWarAirplane drawingWarAirplane, char separatorForObject)
{
var warAirplane = drawingWarAirplane.EntityWarAirplane;
if(warAirplane == null)
{
return string.Empty;
}
var str = $"{warAirplane.Speed}{separatorForObject}{warAirplane.Weight}" +
$"{separatorForObject}{warAirplane.BodyColor.Name}";
if(warAirplane is not EntityAirBomber airBomber)
{
return str;
}
return $"{str}{separatorForObject}{airBomber.AdditionalColor.Name}{separatorForObject}" +
$"{airBomber.FuelTank}{separatorForObject}{airBomber.Bombs}";
}
}
}

View File

@@ -40,13 +40,24 @@
buttonAdd = new Button();
maskedTextBoxNumber = new MaskedTextBox();
pictureBoxCollection = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
SaveToolStripMenuItem = new ToolStripMenuItem();
LoadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
ButtonSortByType = new Button();
ButtonSortByColor = new Button();
panelCollection.SuspendLayout();
panelObject.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// panelCollection
//
panelCollection.Controls.Add(ButtonSortByColor);
panelCollection.Controls.Add(ButtonSortByType);
panelCollection.Controls.Add(panelObject);
panelCollection.Controls.Add(Tools);
panelCollection.Controls.Add(buttonRefreshCollection);
@@ -54,9 +65,9 @@
panelCollection.Controls.Add(buttonAdd);
panelCollection.Controls.Add(maskedTextBoxNumber);
panelCollection.Dock = DockStyle.Right;
panelCollection.Location = new Point(617, 0);
panelCollection.Location = new Point(617, 24);
panelCollection.Name = "panelCollection";
panelCollection.Size = new Size(183, 450);
panelCollection.Size = new Size(183, 574);
panelCollection.TabIndex = 0;
//
// panelObject
@@ -118,7 +129,7 @@
//
// buttonRefreshCollection
//
buttonRefreshCollection.Location = new Point(3, 395);
buttonRefreshCollection.Location = new Point(3, 519);
buttonRefreshCollection.Name = "buttonRefreshCollection";
buttonRefreshCollection.Size = new Size(174, 43);
buttonRefreshCollection.TabIndex = 2;
@@ -128,7 +139,7 @@
//
// buttonRemove
//
buttonRemove.Location = new Point(3, 336);
buttonRemove.Location = new Point(3, 468);
buttonRemove.Name = "buttonRemove";
buttonRemove.Size = new Size(174, 31);
buttonRemove.TabIndex = 2;
@@ -138,7 +149,7 @@
//
// buttonAdd
//
buttonAdd.Location = new Point(3, 255);
buttonAdd.Location = new Point(3, 381);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(174, 31);
buttonAdd.TabIndex = 2;
@@ -148,7 +159,7 @@
//
// maskedTextBoxNumber
//
maskedTextBoxNumber.Location = new Point(3, 307);
maskedTextBoxNumber.Location = new Point(3, 439);
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(174, 23);
maskedTextBoxNumber.TabIndex = 0;
@@ -156,19 +167,79 @@
// pictureBoxCollection
//
pictureBoxCollection.Dock = DockStyle.Left;
pictureBoxCollection.Location = new Point(0, 0);
pictureBoxCollection.Location = new Point(0, 24);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(617, 450);
pictureBoxCollection.Size = new Size(617, 574);
pictureBoxCollection.TabIndex = 1;
pictureBoxCollection.TabStop = false;
//
// menuStrip
//
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(800, 24);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { SaveToolStripMenuItem, LoadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(48, 20);
файлToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
SaveToolStripMenuItem.Size = new Size(133, 22);
SaveToolStripMenuItem.Text = "Сохранить";
SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// LoadToolStripMenuItem
//
LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
LoadToolStripMenuItem.Size = new Size(133, 22);
LoadToolStripMenuItem.Text = "Загрузить";
LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// openFileDialog
//
openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// ButtonSortByType
//
ButtonSortByType.Location = new Point(3, 266);
ButtonSortByType.Name = "ButtonSortByType";
ButtonSortByType.Size = new Size(174, 40);
ButtonSortByType.TabIndex = 5;
ButtonSortByType.Text = "Сортировать по типу";
ButtonSortByType.UseVisualStyleBackColor = true;
ButtonSortByType.Click += ButtonSortByType_Click;
//
// ButtonSortByColor
//
ButtonSortByColor.Location = new Point(3, 312);
ButtonSortByColor.Name = "ButtonSortByColor";
ButtonSortByColor.Size = new Size(174, 40);
ButtonSortByColor.TabIndex = 6;
ButtonSortByColor.Text = "Сортировать по цвету";
ButtonSortByColor.UseVisualStyleBackColor = true;
ButtonSortByColor.Click += ButtonSortByColor_Click;
//
// FormWarAirplaneCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
ClientSize = new Size(800, 598);
Controls.Add(pictureBoxCollection);
Controls.Add(panelCollection);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormWarAirplaneCollection";
Text = "Набор военных самолётов";
panelCollection.ResumeLayout(false);
@@ -176,7 +247,10 @@
panelObject.ResumeLayout(false);
panelObject.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
@@ -193,5 +267,13 @@
private Button buttonDelObject;
private Panel panelObject;
private TextBox textBoxStorageName;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Button ButtonSortByColor;
private Button ButtonSortByType;
}
}

View File

@@ -10,16 +10,20 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AirBomber.Exceptions;
using Microsoft.Extensions.Logging;
namespace AirBomber
{
public partial class FormWarAirplaneCollection : Form
{
private readonly WarAirplaneGenericStorage _storage;
public FormWarAirplaneCollection()
private readonly ILogger _logger;
public FormWarAirplaneCollection(ILogger<FormWarAirplaneCollection> logger)
{
InitializeComponent();
_storage = new WarAirplaneGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
}
private void ReloadObjects()
{
@@ -28,7 +32,7 @@ namespace AirBomber
listBoxStorages.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++)
{
listBoxStorages.Items.Add(_storage.Keys[i]);
listBoxStorages.Items.Add(_storage.Keys[i].Name);
}
if (listBoxStorages.Items.Count > 0 && (index == -1 || index
@@ -53,11 +57,13 @@ namespace AirBomber
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
}
private void ButtonDelObject__Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
_logger.LogWarning("Удаление невыбранного набора");
return;
}
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление",
@@ -66,8 +72,9 @@ namespace AirBomber
_storage.DelSet(listBoxStorages.SelectedItem.ToString()
?? string.Empty);
ReloadObjects();
_logger.LogInformation($"Удален набор: {textBoxStorageName.Text}");
}
_logger.LogWarning("Отмена удаления набора");
}
private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e)
{
@@ -84,28 +91,49 @@ namespace AirBomber
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
FormAirBomber form = new();
if (form.ShowDialog() == DialogResult.OK)
FormWarAirplaneConfig form = new FormWarAirplaneConfig();
form.Show();
Action<DrawingWarAirplane>? warAirplaneDelegate = new((m) =>
{
if (obj + form.SelectedWarAirplane)
try
{
bool q = obj + m;
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Добавлен объект в коллекцию {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
pictureBoxCollection.Image = obj.ShowWarAirplane();
}
else
catch (StorageOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogInformation($"Коллекция {listBoxStorages.SelectedItem.ToString() ?? string.Empty} переполнена");
MessageBox.Show(ex.Message);
}
}
catch (ArgumentException ex)
{
_logger.LogInformation($"Добавляемый объект уже существует в коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
MessageBox.Show("Добавляемый объект уже сущесвует в коллекции");
}
});
Action<Color>? ColorDelegate = new((m) =>
{
MessageBox.Show(m.ToString());
});
form.AddEvent(warAirplaneDelegate);
}
private void ButtonRemoveWarAirplane_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
_logger.LogWarning("Удаление объекта из несуществующего набора");
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
@@ -117,17 +145,28 @@ namespace AirBomber
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
_logger.LogWarning("Отмена удаления объекта");
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos != null)
try
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowWarAirplane();
if (obj - pos != null)
{
MessageBox.Show("Объект удален");
_logger.LogInformation($"Удален объект с позиции {pos}");
pictureBoxCollection.Image = obj.ShowWarAirplane();
}
else
{
_logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorages.SelectedItem.ToString()}");
MessageBox.Show("Не удалось удалить объект");
}
}
else
catch(WarAirplaneNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show(ex.Message);
_logger.LogWarning($"{ex.Message} из {listBoxStorages.SelectedItem.ToString()}");
}
}
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
@@ -144,6 +183,69 @@ namespace AirBomber
}
pictureBoxCollection.Image = obj.ShowWarAirplane();
}
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Данные загружены в файл {saveFileDialog.FileName}");
}
catch(Exception ex)
{
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не удалось сохранить информацию в файл: {ex.Message}");
}
}
}
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
foreach (var collection in _storage.Keys)
{
listBoxStorages.Items.Add(collection);
}
_logger.LogInformation($"Данные загружены из файла {openFileDialog.FileName}");
}
catch(Exception ex)
{
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не удалось загрузить информацию из файла: {ex.Message}");
}
}
}
private void CompareWarAirplane(IComparer<DrawingWarAirplane?> comparer)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
obj.Sort(comparer);
pictureBoxCollection.Image = obj.ShowWarAirplane();
}
private void ButtonSortByType_Click(object sender, EventArgs e) => CompareWarAirplane(new WarAirplaneCompareByType());
private void ButtonSortByColor_Click(object sender, EventArgs e) => CompareWarAirplane(new WarAirplaneCompareByColor());
}
}

View File

@@ -117,4 +117,13 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>132, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>271, 17</value>
</metadata>
</root>

View File

@@ -0,0 +1,370 @@
namespace AirBomber
{
partial class FormWarAirplaneConfig
{
/// <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()
{
groupBoxParameters = new GroupBox();
labelModifiedObject = new Label();
labelSimpleObject = new Label();
checkBoxBombs = new CheckBox();
checkBoxFuelTank = new CheckBox();
numericUpDownWeight = new NumericUpDown();
numericUpDownSpeed = new NumericUpDown();
labelWeight = new Label();
labelSpeed = new Label();
groupBoxColors = new GroupBox();
panelPurple = new Panel();
panelBlack = new Panel();
panelGray = new Panel();
panelWhite = new Panel();
panelYellow = new Panel();
panelBlue = new Panel();
panelGreen = new Panel();
panelRed = new Panel();
groupBoxObject = new GroupBox();
panelObject = new Panel();
pictureBoxObject = new PictureBox();
labelAddColor = new Label();
labelColor = new Label();
buttonAdd = new Button();
buttonCancel = new Button();
groupBoxParameters.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
groupBoxColors.SuspendLayout();
groupBoxObject.SuspendLayout();
panelObject.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
SuspendLayout();
//
// groupBoxParameters
//
groupBoxParameters.Controls.Add(labelModifiedObject);
groupBoxParameters.Controls.Add(labelSimpleObject);
groupBoxParameters.Controls.Add(checkBoxBombs);
groupBoxParameters.Controls.Add(checkBoxFuelTank);
groupBoxParameters.Controls.Add(numericUpDownWeight);
groupBoxParameters.Controls.Add(numericUpDownSpeed);
groupBoxParameters.Controls.Add(labelWeight);
groupBoxParameters.Controls.Add(labelSpeed);
groupBoxParameters.Controls.Add(groupBoxColors);
groupBoxParameters.Location = new Point(11, 12);
groupBoxParameters.Name = "groupBoxParameters";
groupBoxParameters.Size = new Size(515, 300);
groupBoxParameters.TabIndex = 0;
groupBoxParameters.TabStop = false;
groupBoxParameters.Text = "Параметры";
//
// labelModifiedObject
//
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.Location = new Point(385, 192);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(90, 50);
labelModifiedObject.TabIndex = 8;
labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
labelModifiedObject.MouseDown += LabelObject_MouseDown;
//
// labelSimpleObject
//
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Location = new Point(251, 192);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(90, 50);
labelSimpleObject.TabIndex = 7;
labelSimpleObject.Text = "Простой";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
labelSimpleObject.MouseDown += LabelObject_MouseDown;
//
// checkBoxBombs
//
checkBoxBombs.AutoSize = true;
checkBoxBombs.Location = new Point(23, 155);
checkBoxBombs.Name = "checkBoxBombs";
checkBoxBombs.Size = new Size(65, 19);
checkBoxBombs.TabIndex = 6;
checkBoxBombs.Text = "Бомбы";
checkBoxBombs.UseVisualStyleBackColor = true;
//
// checkBoxFuelTank
//
checkBoxFuelTank.AutoSize = true;
checkBoxFuelTank.Location = new Point(23, 120);
checkBoxFuelTank.Name = "checkBoxFuelTank";
checkBoxFuelTank.Size = new Size(210, 19);
checkBoxFuelTank.TabIndex = 5;
checkBoxFuelTank.Text = "Дополнительный топливный бак";
checkBoxFuelTank.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(105, 70);
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(120, 23);
numericUpDownWeight.TabIndex = 4;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(105, 37);
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(120, 23);
numericUpDownSpeed.TabIndex = 3;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelWeight
//
labelWeight.AutoSize = true;
labelWeight.Location = new Point(25, 72);
labelWeight.Name = "labelWeight";
labelWeight.Size = new Size(29, 15);
labelWeight.TabIndex = 2;
labelWeight.Text = "Вес:";
//
// labelSpeed
//
labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(25, 39);
labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(62, 15);
labelSpeed.TabIndex = 1;
labelSpeed.Text = "Скорость:";
//
// groupBoxColors
//
groupBoxColors.Controls.Add(panelPurple);
groupBoxColors.Controls.Add(panelBlack);
groupBoxColors.Controls.Add(panelGray);
groupBoxColors.Controls.Add(panelWhite);
groupBoxColors.Controls.Add(panelYellow);
groupBoxColors.Controls.Add(panelBlue);
groupBoxColors.Controls.Add(panelGreen);
groupBoxColors.Controls.Add(panelRed);
groupBoxColors.Location = new Point(240, 24);
groupBoxColors.Name = "groupBoxColors";
groupBoxColors.Size = new Size(248, 150);
groupBoxColors.TabIndex = 0;
groupBoxColors.TabStop = false;
groupBoxColors.Text = "Цвета";
//
// panelPurple
//
panelPurple.BackColor = Color.Purple;
panelPurple.Location = new Point(190, 85);
panelPurple.Name = "panelPurple";
panelPurple.Size = new Size(45, 45);
panelPurple.TabIndex = 7;
//
// panelBlack
//
panelBlack.BackColor = Color.Black;
panelBlack.Location = new Point(132, 85);
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(45, 45);
panelBlack.TabIndex = 6;
//
// panelGray
//
panelGray.BackColor = Color.FromArgb(64, 64, 64);
panelGray.Location = new Point(72, 85);
panelGray.Name = "panelGray";
panelGray.Size = new Size(45, 45);
panelGray.TabIndex = 5;
//
// panelWhite
//
panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(11, 85);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(45, 45);
panelWhite.TabIndex = 4;
//
// panelYellow
//
panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(190, 24);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(45, 45);
panelYellow.TabIndex = 3;
//
// panelBlue
//
panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(132, 24);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(45, 45);
panelBlue.TabIndex = 2;
//
// panelGreen
//
panelGreen.BackColor = Color.Green;
panelGreen.Location = new Point(72, 24);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(45, 45);
panelGreen.TabIndex = 1;
//
// panelRed
//
panelRed.BackColor = Color.Red;
panelRed.Location = new Point(11, 24);
panelRed.Name = "panelRed";
panelRed.Size = new Size(45, 45);
panelRed.TabIndex = 0;
//
// groupBoxObject
//
groupBoxObject.Controls.Add(panelObject);
groupBoxObject.Location = new Point(532, 11);
groupBoxObject.Name = "groupBoxObject";
groupBoxObject.Size = new Size(256, 268);
groupBoxObject.TabIndex = 1;
groupBoxObject.TabStop = false;
//
// panelObject
//
panelObject.AllowDrop = true;
panelObject.Controls.Add(pictureBoxObject);
panelObject.Controls.Add(labelAddColor);
panelObject.Controls.Add(labelColor);
panelObject.Location = new Point(6, 22);
panelObject.Name = "panelObject";
panelObject.Size = new Size(244, 240);
panelObject.TabIndex = 3;
panelObject.DragDrop += PanelObject_DragDrop;
panelObject.DragEnter += PanelObject_DragEnter;
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(8, 65);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(224, 172);
pictureBoxObject.TabIndex = 2;
pictureBoxObject.TabStop = false;
//
// labelAddColor
//
labelAddColor.AllowDrop = true;
labelAddColor.BorderStyle = BorderStyle.FixedSingle;
labelAddColor.Location = new Point(123, 16);
labelAddColor.Name = "labelAddColor";
labelAddColor.Size = new Size(109, 40);
labelAddColor.TabIndex = 1;
labelAddColor.Text = "Дополнительный цвет";
labelAddColor.TextAlign = ContentAlignment.MiddleCenter;
labelAddColor.DragDrop += LabelAddColor_DragDrop;
labelAddColor.DragEnter += LabelColor_DragEnter;
//
// labelColor
//
labelColor.AllowDrop = true;
labelColor.BorderStyle = BorderStyle.FixedSingle;
labelColor.Location = new Point(8, 16);
labelColor.Name = "labelColor";
labelColor.Size = new Size(109, 40);
labelColor.TabIndex = 0;
labelColor.Text = "Основной цвет";
labelColor.TextAlign = ContentAlignment.MiddleCenter;
labelColor.DragDrop += LabelColor_DragDrop;
labelColor.DragEnter += LabelColor_DragEnter;
//
// buttonAdd
//
buttonAdd.Location = new Point(538, 285);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(105, 29);
buttonAdd.TabIndex = 2;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += buttonAdd_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(687, 285);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(97, 27);
buttonCancel.TabIndex = 3;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += buttonCancel_Click;
//
// FormWarAirplaneConfig
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 336);
Controls.Add(buttonCancel);
Controls.Add(buttonAdd);
Controls.Add(groupBoxObject);
Controls.Add(groupBoxParameters);
Name = "FormWarAirplaneConfig";
Text = "FormWarAirplaneConfig";
groupBoxParameters.ResumeLayout(false);
groupBoxParameters.PerformLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).EndInit();
groupBoxColors.ResumeLayout(false);
groupBoxObject.ResumeLayout(false);
panelObject.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)pictureBoxObject).EndInit();
ResumeLayout(false);
}
#endregion
private GroupBox groupBoxParameters;
private Label labelSpeed;
private GroupBox groupBoxColors;
private GroupBox groupBoxObject;
private Label labelModifiedObject;
private Label labelSimpleObject;
private CheckBox checkBoxBombs;
private CheckBox checkBoxFuelTank;
private NumericUpDown numericUpDownWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelWeight;
private Panel panelPurple;
private Panel panelBlack;
private Panel panelGray;
private Panel panelWhite;
private Panel panelYellow;
private Panel panelBlue;
private Panel panelGreen;
private Panel panelRed;
private PictureBox pictureBoxObject;
private Label labelAddColor;
private Label labelColor;
private Button buttonAdd;
private Button buttonCancel;
private Panel panelObject;
}
}

View File

@@ -0,0 +1,149 @@
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 AirBomber.DrawingObjects;
namespace AirBomber
{
public partial class FormWarAirplaneConfig : Form
{
DrawingWarAirplane? _WarAirplane = null;
public event Action<DrawingWarAirplane>? EventAddWarAirplane;
public FormWarAirplaneConfig()
{
InitializeComponent();
panelBlack.MouseDown += PanelColor_MouseDown;
panelPurple.MouseDown += PanelColor_MouseDown;
panelYellow.MouseDown += PanelColor_MouseDown;
panelWhite.MouseDown += PanelColor_MouseDown;
panelGreen.MouseDown += PanelColor_MouseDown;
panelGray.MouseDown += PanelColor_MouseDown;
panelBlue.MouseDown += PanelColor_MouseDown;
panelRed.MouseDown += PanelColor_MouseDown;
buttonCancel.Click += (s, e) => Close();
}
private void DrawWarAirplane()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_WarAirplane?.SetPosition(5, 5);
_WarAirplane?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
private void PanelColor_MouseDown(object sender, MouseEventArgs e)
{
(sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor,
DragDropEffects.Move | DragDropEffects.Copy);
}
private void LabelColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)))
e.Effect = DragDropEffects.Copy;
else
{
e.Effect = DragDropEffects.None;
}
}
private void LabelColor_DragDrop(object sender, DragEventArgs e)
{
if (_WarAirplane is DrawingWarAirplane WarAirplane)
{
labelColor.BackColor = (Color)e.Data.GetData(typeof(Color));
_WarAirplane.setColor((Color)e.Data.GetData(typeof(Color)));
}
DrawWarAirplane();
}
private void LabelAddColor_DragDrop(object sender, DragEventArgs e)
{
if (_WarAirplane is DrawingAirBomber WarAirplane)
{
labelAddColor.BackColor = (Color)e.Data.GetData(typeof(Color));
((DrawingAirBomber)_WarAirplane).setAddColor((Color)e.Data.GetData(typeof(Color)));
}
DrawWarAirplane();
}
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)
{
switch (e.Data?.GetData(DataFormats.Text).ToString())
{
case "labelSimpleObject":
_WarAirplane = new DrawingWarAirplane((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, pictureBoxObject.Width,
pictureBoxObject.Height);
labelColor.BackColor = Color.White;
labelAddColor.BackColor = Color.Transparent;
break;
case "labelModifiedObject":
_WarAirplane = new DrawingAirBomber((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, Color.Black, checkBoxFuelTank.Checked,
checkBoxBombs.Checked, pictureBoxObject.Width,
pictureBoxObject.Height);
labelColor.BackColor = Color.White;
labelAddColor.BackColor = Color.Black;
break;
}
DrawWarAirplane();
}
public void AddEvent(Action<DrawingWarAirplane> ev)
{
if (EventAddWarAirplane == null)
{
EventAddWarAirplane = ev;
}
else
{
EventAddWarAirplane += ev;
}
}
private void buttonAdd_Click(object sender, EventArgs e)
{
EventAddWarAirplane?.Invoke(_WarAirplane);
Close();
}
private void buttonCancel_Click(object sender, EventArgs e)
{
Close();
}
}
}

View File

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

View File

@@ -1,3 +1,28 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.VisualBasic.Logging;
using Serilog;
using Serilog.Events;
using Serilog.Formatting.Json;
using Log = Serilog.Log;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Core;
using Serilog.Events;
using Serilog.Formatting.Json;
using System;
using System.IO;
using System.Windows.Forms;
namespace AirBomber
{
internal static class Program
@@ -6,12 +31,48 @@ namespace AirBomber
/// 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 FormWarAirplaneCollection());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormWarAirplaneCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
string path = Directory.GetCurrentDirectory();
path = path.Substring(0, path.LastIndexOf("\\"));
path = path.Substring(0, path.LastIndexOf("\\"));
path = path.Substring(0, path.LastIndexOf("\\"));
services.AddSingleton<FormWarAirplaneCollection>()
.AddLogging(option =>
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: path + "\\appSetting.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
logger.Information("<22><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD>");
});
}
}
}
}

View File

@@ -1,4 +1,5 @@
using System;
using AirBomber.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -8,68 +9,62 @@ namespace AirBomber.Generics
{
internal class SetGeneric<T>
where T : class
{
private readonly List<T?> _places;
public int Count => _places.Count;
public int startPointer = 0;
public readonly int _maxCount;
public int countMax = 0;
public SetGeneric(int count)
{
_maxCount = count;
_places = new List<T?>(count);
countMax = count;
}
public bool Insert(T WarAirplane)
public bool Insert(T car, IEqualityComparer<T>? equal = null)
{
if (_places.Count == _maxCount)
{
return false;
}
Insert(WarAirplane, 0);
if (_places.Count == countMax) { throw new StorageOverflowException(countMax); }
Insert(car, 0, equal);
return true;
}
public bool Insert(T WarAirplane, int position)
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
public bool Insert(T warAirplane, int position, IEqualityComparer<T>? equal = null)
{
if (!(position >= 0 && position <= Count && _places.Count < _maxCount))
{
return false;
}
_places.Insert(position, WarAirplane);
if (_places.Count == countMax)
throw new StorageOverflowException(countMax);
if (!(position >= 0 && position <= Count)) return false;
if (equal != null)
{
if (_places.Contains(warAirplane, equal))
throw new ArgumentException(nameof(warAirplane));
}
_places.Insert(position, warAirplane);
return true;
}
public bool Remove(int position)
{
if (position < 0 || position >= Count)
{
return false;
}
if (!(position >= 0 && position < Count))
throw new WarAirplaneNotFoundException(position);
_places.RemoveAt(position);
return true;
}
public T? this[int position]
{
get
{
if (position < 0 || position >= _maxCount)
{
if (!(position >= 0 && position < Count))
return null;
}
return _places[position];
}
set
{
if (!(position >= 0 && position < Count && _places.Count < _maxCount))
{
if (!(position >= 0 && position < Count && _places.Count < countMax))
return;
}
_places.Insert(position, value);
return;
}
}
public IEnumerable<T?> GetWarAirplane(int? maxWarAirplane = null)
@@ -83,6 +78,11 @@ namespace AirBomber.Generics
}
}
}
public T? Get(int position)
{
if (position < Count && position >= 0) { return _places[position]; }
return null;
}
}
}

View File

@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace AirBomber.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

@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirBomber
{
internal class WarAirplaneCollectionInfo : IEquatable<WarAirplaneCollectionInfo>
{
public string Name { get; private set; }
public string Description { get; private set; }
public WarAirplaneCollectionInfo(string name, string description)
{
Name = name;
Description = description;
}
public bool Equals(WarAirplaneCollectionInfo? other)
{
if (other == null || other.Name == null)
throw new ArgumentNullException(nameof(other));
return Name == other.Name;
}
public override int GetHashCode()
{
return this.Name.GetHashCode();
}
}
}

View File

@@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AirBomber.DrawingObjects;
namespace AirBomber
{
internal class WarAirplaneCompareByColor : IComparer<DrawingWarAirplane?>
{
public int Compare(DrawingWarAirplane? x, DrawingWarAirplane? y)
{
if (x == null || x.EntityWarAirplane == null)
throw new ArgumentNullException(nameof(x));
if (y == null || y.EntityWarAirplane == null)
throw new ArgumentNullException(nameof(y));
if (x.EntityWarAirplane.BodyColor.Name != y.EntityWarAirplane.BodyColor.Name)
{
return x.EntityWarAirplane.BodyColor.Name.CompareTo(y.EntityWarAirplane.BodyColor.Name);
}
var speedCompare = x.EntityWarAirplane.Speed.CompareTo(y.EntityWarAirplane.Speed);
if (speedCompare != 0)
return speedCompare;
return x.EntityWarAirplane.Weight.CompareTo(y.EntityWarAirplane.Weight);
}
}
}

View File

@@ -0,0 +1,35 @@
using AirBomber.DrawingObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirBomber
{
internal class WarAirplaneCompareByType : IComparer<DrawingWarAirplane?>
{
public int Compare(DrawingWarAirplane? x, DrawingWarAirplane? y)
{
if (x == null || x.EntityWarAirplane == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityWarAirplane == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare =
x.EntityWarAirplane.Speed.CompareTo(y.EntityWarAirplane.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityWarAirplane.Weight.CompareTo(y.EntityWarAirplane.Weight);
}
}
}

View File

@@ -1,5 +1,6 @@
using AirBomber.MovementStrategy;
using AirBomber.DrawingObjects;
using AirBomber.Generics;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -18,6 +19,8 @@ namespace AirBomber.Generics
private readonly int _placeSizeWidth = 110;
private readonly int _placeSizeHeight = 110;
private readonly SetGeneric<T> _collection;
public IEnumerable<T?> GetWarAirplanes => _collection.GetWarAirplane();
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
public WarAirplaneGenericCollection(int picWidth, int picHeight)
{
int width = picWidth / _placeSizeWidth;
@@ -33,7 +36,7 @@ namespace AirBomber.Generics
{
return false;
}
return collect?._collection.Insert(obj) ?? false;
return collect?._collection.Insert(obj, new DrawingWarAirplaneEqutables()) ?? false;
}
public static bool operator -(WarAirplaneGenericCollection<T, U> collect, int
pos)

View File

@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Text;
using System.Threading.Tasks;
using AirBomber.DrawingObjects;
@@ -10,46 +11,132 @@ namespace AirBomber.Generics
{
internal class WarAirplaneGenericStorage
{
readonly Dictionary<string, WarAirplaneGenericCollection<DrawingWarAirplane,
readonly Dictionary<WarAirplaneCollectionInfo, WarAirplaneGenericCollection<DrawingWarAirplane,
DrawingObjectWarAirplane>> _warAirplaneStorages;
public List<string> Keys => _warAirplaneStorages.Keys.ToList();
public List<WarAirplaneCollectionInfo> Keys => _warAirplaneStorages.Keys.ToList();
private readonly int _pictureWidth;
private readonly int _pictureHeight;
private static readonly char _separatorForKeyValue = '|';
private readonly char _separatorRecords = ';';
private static readonly char _separatorForObject = ':';
public WarAirplaneGenericStorage(int pictureWidth, int pictureHeight)
{
_warAirplaneStorages = new Dictionary<string, WarAirplaneGenericCollection<DrawingWarAirplane, DrawingObjectWarAirplane>>();
_warAirplaneStorages = new Dictionary<WarAirplaneCollectionInfo, WarAirplaneGenericCollection<DrawingWarAirplane, DrawingObjectWarAirplane>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
public void AddSet(string name)
{
_warAirplaneStorages.Add(name, new WarAirplaneGenericCollection<DrawingWarAirplane, DrawingObjectWarAirplane>(_pictureWidth, _pictureHeight));
if (_warAirplaneStorages.ContainsKey(new WarAirplaneCollectionInfo(name, string.Empty)))
{
return;
}
_warAirplaneStorages.Add(new WarAirplaneCollectionInfo(name,string.Empty), new WarAirplaneGenericCollection<DrawingWarAirplane, DrawingObjectWarAirplane>(_pictureWidth, _pictureHeight));
}
public void DelSet(string name)
{
if (!_warAirplaneStorages.ContainsKey(name))
if (!_warAirplaneStorages.ContainsKey(new WarAirplaneCollectionInfo(name, string.Empty)))
{
return;
}
_warAirplaneStorages.Remove(name);
_warAirplaneStorages.Remove(new WarAirplaneCollectionInfo(name, string.Empty));
}
/// <summary>
/// Доступ к набору
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public WarAirplaneGenericCollection<DrawingWarAirplane, DrawingObjectWarAirplane>? this[string ind]
{
get
{
if (_warAirplaneStorages.ContainsKey(ind))
WarAirplaneCollectionInfo indObj = new WarAirplaneCollectionInfo(ind, string.Empty);
if (_warAirplaneStorages.ContainsKey(indObj))
{
return _warAirplaneStorages[ind];
return _warAirplaneStorages[indObj];
}
return null;
}
}
public bool SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach(KeyValuePair<WarAirplaneCollectionInfo,WarAirplaneGenericCollection<
DrawingWarAirplane,DrawingObjectWarAirplane>> record in _warAirplaneStorages)
{
StringBuilder records = new();
foreach(DrawingWarAirplane? elem in record.Value.GetWarAirplanes)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key.Name}{_separatorForKeyValue}{records}");
}
if(data.Length == 0)
{
throw new Exception("Невалидная операция, нет данных для сохранения");
}
using FileStream fs = new(filename, FileMode.Create);
byte[] info = new UTF8Encoding(true).GetBytes($"WarAirplaneStorage" +
$"{Environment.NewLine}{data}");
fs.Write(info, 0, info.Length);
return true;
}
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new Exception("Файл не найден");
}
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);
}
}
var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' },
StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
throw new Exception("Нет данных для загрузки");
}
if (!strs[0].StartsWith("WarAirplaneStorage"))
{
throw new Exception("Неверный формат данных");
}
_warAirplaneStorages.Clear();
foreach (string data in strs)
{
string[] record = data.Split(_separatorForKeyValue,
StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
continue;
}
WarAirplaneGenericCollection<DrawingWarAirplane, DrawingObjectWarAirplane>
collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawingWarAirplane? warAirplane = elem?.CreateDrawingWarAirplane(_separatorForObject, _pictureWidth, _pictureHeight);
if(warAirplane != null)
{
if(!(collection + warAirplane))
{
throw new Exception("Ошибка добавления в коллекцию");
}
}
}
_warAirplaneStorages.Add(new WarAirplaneCollectionInfo(record[0], string.Empty), collection);
}
return true;
}
}
}

View File

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

View File

@@ -0,0 +1,20 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "C:\\Users\\user\\source\\repos\\PIbd-23_Bakshaeva_E.A._AirBomber_Base\\AirBomber\\AirBomber\\Logs\\log.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "AirBomber"
}
}
}