6 Commits
Lab06 ... Lab08

15 changed files with 482 additions and 61 deletions

View File

@@ -6,7 +6,7 @@ using System.Threading.Tasks;
namespace Stormtrooper
{
internal abstract class AbstractMap
internal abstract class AbstractMap : IEquatable<AbstractMap>
{
private IDrawningObject _drawningObject = null;
protected int[,] _map = null;
@@ -43,9 +43,9 @@ namespace Stormtrooper
case Direction.Left:
for (int i = LefTopX; i >= Math.Abs(LefTopX - Convert.ToInt32(_drawningObject.Step / _size_x)); i--)
{
for (int j = LefTopY; j <= objheigh && j<_map.GetLength(1); j++)
for (int j = LefTopY; j <= objheigh && j < _map.GetLength(1); j++)
{
if (_map[i, j] == _barrier)
{
CanStep = false;
@@ -67,7 +67,7 @@ namespace Stormtrooper
}
}
}
break;
case Direction.Down:
@@ -83,12 +83,12 @@ namespace Stormtrooper
}
}
}
break;
case Direction.Up:
for (int i = LefTopX; i <= objwidth && i<_map.GetLength(0); i++)
for (int i = LefTopX; i <= objwidth && i < _map.GetLength(0); i++)
{
for (int j = LefTopY; j >= Math.Abs(LefTopY - Convert.ToInt32(_drawningObject.Step / _size_y)) ; j--)
for (int j = LefTopY; j >= Math.Abs(LefTopY - Convert.ToInt32(_drawningObject.Step / _size_y)); j--)
{
if (_map[i, j] == _barrier)
{
@@ -142,7 +142,7 @@ namespace Stormtrooper
Graphics gr = Graphics.FromImage(bmp);
for (int i = 0; i < _map.GetLength(0); ++i)
for (int j = 0; j < _map.GetLength(1); ++j)
DrawRoadPart(gr, i, j);
DrawRoadPart(gr, i, j);
for (int i = 0; i < _map.GetLength(0); ++i)
for (int j = 0; j < _map.GetLength(1); ++j)
@@ -154,5 +154,36 @@ namespace Stormtrooper
protected abstract void GenerateMap();
protected abstract void DrawRoadPart(Graphics g, int i, int j);
protected abstract void DrawBarrierPart(Graphics g, int i, int j);
public bool Equals(AbstractMap? other)
{
if (other == null)
{
return false;
}
if (_width == other._width && _height == other._height && _size_x == other._size_x && _size_y == other._size_y)
{
if (_map == null && other._map == null)
{
return true;
}
if (_map == null || other._map == null || _map.GetLength(0) != other._map.GetLength(0) || _map.GetLength(1) != other._map.GetLength(1))
{
return false;
}
for (int i = 0; i < _map.GetLength(0); i++)
{
for (int j = 0; j < _map.GetLength(1); j++)
{
if (_map[i, j] != other._map[i, j])
{
return false;
}
}
}
return true;
}
return false;
}
}
}

View File

@@ -14,6 +14,7 @@ namespace Stormtrooper
_storm = storm;
}
public float Step => _storm?.Storm?.Step ?? 0;
public Drawning GetStormtrooper => _storm;
public (float Left, float Right, float Top, float Bottom) GetCurrentPosition()
{
return _storm?.GetCurrentPosition() ?? default;
@@ -35,5 +36,52 @@ namespace Stormtrooper
public string GetInfo() => _storm?.GetDataForSave();
public static IDrawningObject Create(string data) => new DrawningObjectStorm(data.CreateDrawningStormtrooper());
public bool Equals(IDrawningObject? other)
{
if (other == null)
{
return false;
}
var otherStormtrooper = other as DrawningObjectStorm;
if (otherStormtrooper == null)
{
return false;
}
var stormtrooper = _storm.Storm;
var otherStormtrooperStormtrooper = otherStormtrooper._storm.Storm;
if (stormtrooper.Speed != otherStormtrooperStormtrooper.Speed)
{
return false;
}
if (stormtrooper.Weight != otherStormtrooperStormtrooper.Weight)
{
return false;
}
if (stormtrooper.BodyColor != otherStormtrooperStormtrooper.BodyColor)
{
return false;
}
if (stormtrooper is EntityMilitaryStormtrooper militaryStorm && otherStormtrooperStormtrooper is EntityMilitaryStormtrooper othermilitaryStorm)
{
if (militaryStorm.DopColor != othermilitaryStorm.DopColor)
{
return false;
}
if (militaryStorm.BodyKit != othermilitaryStorm.BodyKit)
{
return false;
}
if (militaryStorm.Rocket != othermilitaryStorm.Rocket)
{
return false;
}
if (militaryStorm.SportLine != othermilitaryStorm.SportLine)
{
return false;
}
}
else if (stormtrooper is EntityMilitaryStormtrooper || otherStormtrooperStormtrooper is EntityMilitaryStormtrooper) return false;
return true;
}
}
}

View File

@@ -29,6 +29,8 @@
private void InitializeComponent()
{
this.groupBoxTools = new System.Windows.Forms.GroupBox();
this.buttonSortByColor = new System.Windows.Forms.Button();
this.buttonSortByType = new System.Windows.Forms.Button();
this.groupBoxMaps = new System.Windows.Forms.GroupBox();
this.listBoxMaps = new System.Windows.Forms.ListBox();
this.buttonDeleteMap = new System.Windows.Forms.Button();
@@ -59,6 +61,8 @@
//
// groupBoxTools
//
this.groupBoxTools.Controls.Add(this.buttonSortByColor);
this.groupBoxTools.Controls.Add(this.buttonSortByType);
this.groupBoxTools.Controls.Add(this.groupBoxMaps);
this.groupBoxTools.Controls.Add(this.maskedTextBoxPosition);
this.groupBoxTools.Controls.Add(this.buttonRemoveCar);
@@ -74,11 +78,31 @@
this.groupBoxTools.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.groupBoxTools.Name = "groupBoxTools";
this.groupBoxTools.Padding = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.groupBoxTools.Size = new System.Drawing.Size(233, 856);
this.groupBoxTools.Size = new System.Drawing.Size(233, 930);
this.groupBoxTools.TabIndex = 0;
this.groupBoxTools.TabStop = false;
this.groupBoxTools.Text = "Инструменты";
//
// buttonSortByColor
//
this.buttonSortByColor.Location = new System.Drawing.Point(20, 446);
this.buttonSortByColor.Name = "buttonSortByColor";
this.buttonSortByColor.Size = new System.Drawing.Size(198, 50);
this.buttonSortByColor.TabIndex = 13;
this.buttonSortByColor.Text = "Сортировать по цвету";
this.buttonSortByColor.UseVisualStyleBackColor = true;
this.buttonSortByColor.Click += new System.EventHandler(this.buttonSortByColor_Click);
//
// buttonSortByType
//
this.buttonSortByType.Location = new System.Drawing.Point(21, 395);
this.buttonSortByType.Name = "buttonSortByType";
this.buttonSortByType.Size = new System.Drawing.Size(198, 45);
this.buttonSortByType.TabIndex = 12;
this.buttonSortByType.Text = "Сортировать по типу";
this.buttonSortByType.UseVisualStyleBackColor = true;
this.buttonSortByType.Click += new System.EventHandler(this.buttonSortByType_Click);
//
// groupBoxMaps
//
this.groupBoxMaps.Controls.Add(this.listBoxMaps);
@@ -148,7 +172,7 @@
//
// maskedTextBoxPosition
//
this.maskedTextBoxPosition.Location = new System.Drawing.Point(21, 511);
this.maskedTextBoxPosition.Location = new System.Drawing.Point(20, 571);
this.maskedTextBoxPosition.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.maskedTextBoxPosition.Mask = "00";
this.maskedTextBoxPosition.Name = "maskedTextBoxPosition";
@@ -158,7 +182,7 @@
//
// buttonRemoveCar
//
this.buttonRemoveCar.Location = new System.Drawing.Point(21, 565);
this.buttonRemoveCar.Location = new System.Drawing.Point(20, 625);
this.buttonRemoveCar.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonRemoveCar.Name = "buttonRemoveCar";
this.buttonRemoveCar.Size = new System.Drawing.Size(200, 47);
@@ -169,7 +193,7 @@
//
// buttonShowStorage
//
this.buttonShowStorage.Location = new System.Drawing.Point(21, 633);
this.buttonShowStorage.Location = new System.Drawing.Point(20, 693);
this.buttonShowStorage.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonShowStorage.Name = "buttonShowStorage";
this.buttonShowStorage.Size = new System.Drawing.Size(200, 47);
@@ -183,7 +207,7 @@
this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDown.BackgroundImage = global::Stormtrooper.Properties.Resources.arrowDown;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonDown.Location = new System.Drawing.Point(104, 789);
this.buttonDown.Location = new System.Drawing.Point(104, 863);
this.buttonDown.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(34, 40);
@@ -196,7 +220,7 @@
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::Stormtrooper.Properties.Resources.arrowRight;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonRight.Location = new System.Drawing.Point(145, 789);
this.buttonRight.Location = new System.Drawing.Point(145, 863);
this.buttonRight.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(34, 40);
@@ -209,7 +233,7 @@
this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonLeft.BackgroundImage = global::Stormtrooper.Properties.Resources.arrowLeft;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonLeft.Location = new System.Drawing.Point(63, 789);
this.buttonLeft.Location = new System.Drawing.Point(63, 863);
this.buttonLeft.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(34, 40);
@@ -222,7 +246,7 @@
this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonUp.BackgroundImage = global::Stormtrooper.Properties.Resources.arrowUp;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonUp.Location = new System.Drawing.Point(104, 741);
this.buttonUp.Location = new System.Drawing.Point(104, 815);
this.buttonUp.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(34, 40);
@@ -232,7 +256,7 @@
//
// buttonShowOnMap
//
this.buttonShowOnMap.Location = new System.Drawing.Point(21, 700);
this.buttonShowOnMap.Location = new System.Drawing.Point(20, 760);
this.buttonShowOnMap.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonShowOnMap.Name = "buttonShowOnMap";
this.buttonShowOnMap.Size = new System.Drawing.Size(200, 47);
@@ -243,7 +267,7 @@
//
// buttonAddCar
//
this.buttonAddCar.Location = new System.Drawing.Point(21, 443);
this.buttonAddCar.Location = new System.Drawing.Point(20, 503);
this.buttonAddCar.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonAddCar.Name = "buttonAddCar";
this.buttonAddCar.Size = new System.Drawing.Size(200, 47);
@@ -258,7 +282,7 @@
this.pictureBox.Location = new System.Drawing.Point(0, 28);
this.pictureBox.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.pictureBox.Name = "pictureBox";
this.pictureBox.Size = new System.Drawing.Size(927, 856);
this.pictureBox.Size = new System.Drawing.Size(927, 930);
this.pictureBox.TabIndex = 1;
this.pictureBox.TabStop = false;
//
@@ -284,14 +308,14 @@
// SaveToolStripMenuItem
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(177, 26);
this.SaveToolStripMenuItem.Text = "Сохранение";
this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// LoadToolStripMenuItem
//
this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(177, 26);
this.LoadToolStripMenuItem.Text = "Загрузка";
this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
@@ -307,7 +331,7 @@
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1160, 884);
this.ClientSize = new System.Drawing.Size(1160, 958);
this.Controls.Add(this.pictureBox);
this.Controls.Add(this.groupBoxTools);
this.Controls.Add(this.menuStrip);
@@ -351,5 +375,7 @@
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@@ -1,4 +1,6 @@
using System;
using Microsoft.Extensions.Logging;
using Serilog.Core;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
@@ -25,13 +27,17 @@ namespace Stormtrooper
/// Объект от коллекции карт
/// </summary>
private readonly MapsCollection _mapsCollection;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormMapWithSetStormtroopers()
public FormMapWithSetStormtroopers(ILogger<FormMapWithSetStormtroopers> logger)
{
InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
comboBoxSelectorMap.Items.Clear();
foreach (var elem in _mapsDict)
@@ -46,28 +52,42 @@ namespace Stormtrooper
/// <param name="e"></param>
private void ButtonAddStorm_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
var formStormConfig = new FormStormtrooperConfig();
formStormConfig.AddEvent(AddStormtrooper);
formStormConfig.Show();
}
private void AddStormtrooper (Drawning storm)
private void AddStormtrooper(Drawning storm)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
DrawningObjectStorm st = new(storm);
try
{
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + st != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
int res = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectStorm(storm);
MessageBox.Show("Объект добавлен");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation($"Добавление объекта: {storm.ToString()}");
}
catch (StorageOverflowException ex)
{
MessageBox.Show($"Не удалось добавить объект: {ex.Message}");
_logger.LogWarning($"Ошибка добавления объекта: {ex.Message}");
}
catch (ArgumentException ex)
{
MessageBox.Show($"Ошибка добавления объекта: {ex.Message}");
_logger.LogWarning($"Ошибка добавления объекта: {ex.Message}");
}
catch (Exception ex)
{
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
_logger.LogWarning($"Ошибка добавления объекта: {ex.Message}");
}
}
/// <summary>
@@ -89,16 +109,26 @@ namespace Stormtrooper
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
try
{
IDrawningObject drawingObject = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos;
MessageBox.Show("Объект удален");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation($"Удаление объекта: {drawingObject.ToString()}");
}
else
catch (StormtrooperNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show($"Ошибка удаления: {ex.Message}");
_logger.LogWarning($"Ошибка удаления объекта: {ex.Message}");
}
catch (Exception ex)
{
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
_logger.LogWarning($"Ошибка удаления объекта: {ex.Message}");
}
}
/// <summary>
/// Вывод набора
@@ -188,11 +218,13 @@ namespace Stormtrooper
}
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps();
_logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}");
}
private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation($"Переход на карту {listBoxMaps.SelectedItem?.ToString() ?? string.Empty}");
}
private void ButtonDeleteMap_Click(object sender, EventArgs e)
@@ -206,6 +238,7 @@ namespace Stormtrooper
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps();
}
_logger.LogInformation($"Удалена карта {listBoxMaps.SelectedItem?.ToString()}");
}
/// <summary>
/// Обработка нажатия "Сохранение"
@@ -216,13 +249,16 @@ namespace Stormtrooper
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.SaveData(saveFileDialog.FileName))
try
{
MessageBox.Show("Сохранение прошло успешно", "Результат",MessageBoxButtons.OK, MessageBoxIcon.Information);
_mapsCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Сохранение данных в файл {saveFileDialog.FileName}");
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат",MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Ошибка сохранения данных: {ex.Message}");
}
}
}
@@ -235,16 +271,47 @@ namespace Stormtrooper
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.LoadData(openFileDialog.FileName))
try
{
_mapsCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadMaps();
_logger.LogInformation($"Загрузка данных из файла {openFileDialog.FileName}");
}
else
catch (Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат",MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Ошибка загрузки данных: {ex.Message}");
}
}
}
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSortByType_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].Sort(new StormtrooperCompareByType());
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSortByColor_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? String.Empty].Sort(new StormtrooperCompareByColor());
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
}
}

View File

@@ -9,7 +9,7 @@ namespace Stormtrooper
/// <summary>
/// Интерфейс для работы с объектом, прорисовываемым на форме
/// </summary>
internal interface IDrawningObject
internal interface IDrawningObject : IEquatable<IDrawningObject>
{
/// <summary>
/// Шаг перемещения объекта

View File

@@ -13,7 +13,7 @@ namespace Stormtrooper
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
internal class MapWithSetStormtroopersGeneric<T, U>
where T : class, IDrawningObject
where T : class, IDrawningObject, IEquatable<T>
where U : AbstractMap
{
/// <summary>
@@ -204,5 +204,13 @@ namespace Stormtrooper
}
}
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer"></param>
public void Sort(IComparer<T> comparer)
{
_setStormtroopers.SortSet(comparer);
}
}
}

View File

@@ -83,7 +83,7 @@ namespace Stormtrooper
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns></returns>
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (File.Exists(filename))
{
@@ -98,18 +98,17 @@ namespace Stormtrooper
sw.WriteLine($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}");
}
}
return true;
}
/// <summary>
/// Загрузка информации по самолётам в ангаре из файла
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public bool LoadData(string filename)
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
throw new FileNotFoundException("Файл не найден");
}
string line;
using (StreamReader sw = new(filename))
@@ -117,7 +116,7 @@ namespace Stormtrooper
line = sw.ReadLine();
if (line == null || !line.Contains("MapsCollection"))
{
return false;
throw new FileFormatException("Неверный формат файла");
}
_mapStorages.Clear();
@@ -142,8 +141,6 @@ namespace Stormtrooper
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
line = sw.ReadLine();
}
return true;
}
}

View File

@@ -1,3 +1,10 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.VisualBasic.Logging;
using Serilog;
using System;
namespace Stormtrooper
{
internal static class Program
@@ -11,7 +18,27 @@ namespace Stormtrooper
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormMapWithSetStormtroopers());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormMapWithSetStormtroopers>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormMapWithSetStormtroopers>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: "serilog.json")
.Build();
Serilog.Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.AddSerilog();
});
}
}
}

View File

@@ -11,7 +11,7 @@ namespace Stormtrooper
/// </summary>
/// <typeparam name="T"></typeparam>
internal class SetStormtroopersGeneric<T>
where T : class
where T : class, IEquatable<T>
{
/// <summary>
/// Список объектов, которые храним
@@ -39,7 +39,6 @@ namespace Stormtrooper
/// <returns></returns>
public int Insert(T stormtrooper)
{
if (_places.Count + 1 >= _maxCount) return -1;
return Insert(stormtrooper, 0);
}
/// <summary>
@@ -50,8 +49,13 @@ namespace Stormtrooper
/// <returns></returns>
public int Insert(T stormtrooper, int position)
{
if (position < 0 || position >= _maxCount) return -1;
if (_places.Count + 1 >= _maxCount) return -1;
foreach (var tec_storm in _places)
{
if ((tec_storm as DrawningObjectStorm).Equals(stormtrooper as DrawningObjectStorm)) throw new ArgumentException("Такой самолёт уже есть");
}
if (position < 0 || position >= _maxCount)
throw new StorageOverflowException(_maxCount);
if (_places.Count >= _maxCount) throw new StorageOverflowException(_maxCount);
_places.Insert(position, stormtrooper);
return position;
}
@@ -62,7 +66,9 @@ namespace Stormtrooper
/// <returns></returns>
public T Remove(int position)
{
if (position < 0 || position >= _maxCount) return null;
if (position < 0 || position >= _maxCount)
throw new StormtrooperNotFoundException();
if (position >= _places.Count) throw new StormtrooperNotFoundException(position);
T saveStorm = _places[position];
_places.RemoveAt(position);
return saveStorm;
@@ -103,5 +109,18 @@ namespace Stormtrooper
}
}
}
/// <summary>
/// Сортировка набора объектов
/// </summary>
/// <param name="comparer"></param>
public void SortSet(IComparer<T> comparer)
{
if (comparer == null)
{
return;
}
_places.Sort(comparer);
}
}
}

View File

@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Stormtrooper
{
[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) { }
protected StorageOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@@ -8,6 +8,28 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<None Remove="serilog.json" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="serilog.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="3.1.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

@@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Stormtrooper
{
internal class StormtrooperCompareByColor : IComparer<IDrawningObject>
{
public int Compare(IDrawningObject? x, IDrawningObject? y)
{
if (x == null && y == null)
{
return 0;
}
if (x == null && y != null)
{
return 1;
}
if (x != null && y == null)
{
return -1;
}
var xStorm = x as DrawningObjectStorm;
var yStorm = y as DrawningObjectStorm;
if (xStorm == null && yStorm == null)
{
return 0;
}
if (xStorm == null && yStorm != null)
{
return 1;
}
if (xStorm != null && yStorm == null)
{
return -1;
}
var baseColorCompare = xStorm.GetStormtrooper.Storm.BodyColor.ToString().CompareTo(yStorm.GetStormtrooper.Storm.BodyColor.ToString());
if (baseColorCompare != 0)
{
return baseColorCompare;
}
if (xStorm.GetStormtrooper.Storm is EntityMilitaryStormtrooper xDDB && yStorm.GetStormtrooper.Storm is EntityMilitaryStormtrooper yDDB)
{
var extraColorCompare = xDDB.BodyColor.ToString().CompareTo(yDDB.BodyColor.ToString());
if (extraColorCompare != 0)
{
return extraColorCompare;
}
}
return 0;
}
}
}

View File

@@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Stormtrooper
{
internal class StormtrooperCompareByType : IComparer<IDrawningObject>
{
public int Compare(IDrawningObject? x, IDrawningObject? y)
{
if (x == null && y == null)
{
return 0;
}
if (x == null && y != null)
{
return 1;
}
if (x != null && y == null)
{
return -1;
}
var xStorm = x as DrawningObjectStorm;
var yStorm = y as DrawningObjectStorm;
if (xStorm == null && yStorm == null)
{
return 0;
}
if (xStorm == null && yStorm != null)
{
return 1;
}
if (xStorm != null && yStorm == null)
{
return -1;
}
if (xStorm.GetStormtrooper.GetType().Name != yStorm.GetStormtrooper.GetType().Name)
{
if (xStorm.GetStormtrooper.GetType().Name == "Drawning")
{
return -1;
}
return 1;
}
var speedCompare = xStorm.GetStormtrooper.Storm.Speed.CompareTo(yStorm.GetStormtrooper.Storm.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return xStorm.GetStormtrooper.Storm.Weight.CompareTo(yStorm.GetStormtrooper.Storm.Weight);
}
}
}

View File

@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Stormtrooper
{
[Serializable]
internal class StormtrooperNotFoundException : ApplicationException
{
public StormtrooperNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
public StormtrooperNotFoundException() : base("Выход за границы") { }
public StormtrooperNotFoundException(string message) : base(message) { }
public StormtrooperNotFoundException(string message, Exception exception) : base(message, exception) { }
protected StormtrooperNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@@ -0,0 +1,24 @@
{
"exclude": [
"**/bin",
"**/bower_components",
"**/jspm_packages",
"**/node_modules",
"**/obj",
"**/platforms"
],
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": { "path": "Logs/log.log" }
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "Sample"
}
}
}