7 Commits
Lab05 ... Lab08

17 changed files with 747 additions and 53 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;
@@ -32,6 +33,55 @@ namespace Stormtrooper
((DrawningMilitary)_storm).DrawTransport(g);
_storm.DrawTransport(g);
}
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

@@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Stormtrooper
{
/// <summary>
/// Расширение для класса DrawningStormtrooper
/// </summary>
internal static class ExtentionStormtrooper
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public static Drawning CreateDrawningStormtrooper(this string info)
{
string[] strs = info.Split(_separatorForObject);
if (strs.Length == 3)
{
return new Drawning(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]));
}
if (strs.Length == 7)
{
return new DrawningMilitary(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]),
Color.FromName(strs[3]), Convert.ToBoolean(strs[4]),
Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]));
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningStormtrooper"></param>
/// <returns></returns>
public static string GetDataForSave(this Drawning drawningStormtrooper)
{
var stormtrooper = drawningStormtrooper.Storm;
var str = $"{stormtrooper.Speed}{_separatorForObject}{stormtrooper.Weight}{_separatorForObject}{stormtrooper.BodyColor.Name}";
if (stormtrooper is not EntityMilitaryStormtrooper militaryStormtrooper)
{
return str;
}
return
$"{str}{_separatorForObject}{militaryStormtrooper.DopColor.Name}{_separatorForObject}{militaryStormtrooper .BodyKit}{_separatorForObject}{militaryStormtrooper.Rocket}{_separatorForObject}{militaryStormtrooper.SportLine}";
}
}
}

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();
@@ -45,13 +47,22 @@
this.buttonShowOnMap = new System.Windows.Forms.Button();
this.buttonAddCar = new System.Windows.Forms.Button();
this.pictureBox = new System.Windows.Forms.PictureBox();
this.menuStrip = new System.Windows.Forms.MenuStrip();
this.FileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.SaveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.LoadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.groupBoxTools.SuspendLayout();
this.groupBoxMaps.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
this.menuStrip.SuspendLayout();
this.SuspendLayout();
//
// 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);
@@ -63,15 +74,35 @@
this.groupBoxTools.Controls.Add(this.buttonShowOnMap);
this.groupBoxTools.Controls.Add(this.buttonAddCar);
this.groupBoxTools.Dock = System.Windows.Forms.DockStyle.Right;
this.groupBoxTools.Location = new System.Drawing.Point(927, 0);
this.groupBoxTools.Location = new System.Drawing.Point(927, 28);
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, 884);
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);
@@ -141,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";
@@ -151,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);
@@ -162,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);
@@ -176,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, 817);
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);
@@ -189,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, 817);
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);
@@ -202,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, 817);
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);
@@ -215,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, 769);
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);
@@ -225,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);
@@ -236,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);
@@ -248,20 +279,63 @@
// pictureBox
//
this.pictureBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBox.Location = new System.Drawing.Point(0, 0);
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, 884);
this.pictureBox.Size = new System.Drawing.Size(927, 930);
this.pictureBox.TabIndex = 1;
this.pictureBox.TabStop = false;
//
// menuStrip
//
this.menuStrip.ImageScalingSize = new System.Drawing.Size(20, 20);
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.FileToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(1160, 28);
this.menuStrip.TabIndex = 2;
//
// FileToolStripMenuItem
//
this.FileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.SaveToolStripMenuItem,
this.LoadToolStripMenuItem});
this.FileToolStripMenuItem.Name = "FileToolStripMenuItem";
this.FileToolStripMenuItem.Size = new System.Drawing.Size(59, 24);
this.FileToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
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(177, 26);
this.LoadToolStripMenuItem.Text = "Загрузка";
this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
// openFileDialog
//
this.openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
this.saveFileDialog.Filter = "txt file | *.txt";
//
// FormMapWithSetStormtroopers
//
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);
this.MainMenuStrip = this.menuStrip;
this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.Name = "FormMapWithSetStormtroopers";
this.Text = "Карта с набором объектов";
@@ -270,7 +344,10 @@
this.groupBoxMaps.ResumeLayout(false);
this.groupBoxMaps.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
@@ -292,5 +369,13 @@
private Button buttonDeleteMap;
private Button buttonAddMap;
private TextBox textBoxNewMapName;
private MenuStrip menuStrip;
private ToolStripMenuItem FileToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
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,80 @@ namespace Stormtrooper
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps();
}
_logger.LogInformation($"Удалена карта {listBoxMaps.SelectedItem?.ToString()}");
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_mapsCollection.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}");
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_mapsCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadMaps();
_logger.LogInformation($"Загрузка данных из файла {openFileDialog.FileName}");
}
catch (Exception ex)
{
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

@@ -57,4 +57,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>144, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>311, 17</value>
</metadata>
</root>

View File

@@ -9,7 +9,7 @@ namespace Stormtrooper
/// <summary>
/// Интерфейс для работы с объектом, прорисовываемым на форме
/// </summary>
internal interface IDrawningObject
internal interface IDrawningObject : IEquatable<IDrawningObject>
{
/// <summary>
/// Шаг перемещения объекта
@@ -38,6 +38,10 @@ namespace Stormtrooper
/// </summary>
/// <returns></returns>
(float Left, float Right, float Top, float Bottom) GetCurrentPosition();
/// <summary>
/// Получение информации по объекту
/// </summary>
/// <returns></returns>
string GetInfo();
}
}

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>
@@ -113,6 +113,33 @@ namespace Stormtrooper
}
return new(_pictureWidth, _pictureHeight);
}
/// <summary>
/// Получение данных в виде строки
/// </summary>
/// <param name="sep"></param>
/// <returns></returns>
public string GetData(char separatorType, char separatorData)
{
string data = $"{_map.GetType().Name}{separatorType}";
foreach (var stormtrooper in _setStormtroopers.GetStormtroopers())
{
data += $"{stormtrooper.GetInfo()}{separatorData}";
}
return data;
}
/// <summary>
/// Загрузка списка из массива строк
/// </summary>
/// <param name="records"></param>
public void LoadData(string[] records)
{
foreach (var rec in records)
{
_setStormtroopers.Insert(DrawningObjectStorm.Create(rec) as T);
}
}
/// <summary>
/// "Взбалтываем" набор, чтобы все элементы оказались в начале
/// </summary>
@@ -177,5 +204,13 @@ namespace Stormtrooper
}
}
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer"></param>
public void Sort(IComparer<T> comparer)
{
_setStormtroopers.SortSet(comparer);
}
}
}

View File

@@ -11,7 +11,7 @@ namespace Stormtrooper
/// <summary>
/// Словарь (хранилище) с картами
/// </summary>
readonly Dictionary<string, MapWithSetStormtroopersGeneric<DrawningObjectStorm, AbstractMap>> _mapStorages;
readonly Dictionary<string, MapWithSetStormtroopersGeneric<IDrawningObject, AbstractMap>> _mapStorages;
/// <summary>
/// Возвращение списка названий карт
/// </summary>
@@ -25,13 +25,21 @@ namespace Stormtrooper
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Разделитель для записи информации по элементу словаря в файл
/// </summary>
private readonly char separatorDict = '|';
/// <summary>
/// Разделитель для записей коллекции данных файл
/// </summary>
private readonly char separatorData = ';';
/// <summary>
/// Конструктор
/// </summary>
/// <param name="pictureWidth"></param>
/// <param name="pictureHeight"></param>
public MapsCollection(int pictureWidth, int pictureHeight)
{
_mapStorages = new Dictionary<string, MapWithSetStormtroopersGeneric<DrawningObjectStorm, AbstractMap>>();
_mapStorages = new Dictionary<string, MapWithSetStormtroopersGeneric<IDrawningObject, AbstractMap>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
@@ -47,7 +55,7 @@ namespace Stormtrooper
MessageBox.Show("Карта с таким названием уже существует!");
return;
}
_mapStorages.Add(name, new MapWithSetStormtroopersGeneric<DrawningObjectStorm, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages.Add(name, new MapWithSetStormtroopersGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
}
/// <summary>
/// Удаление карты
@@ -62,15 +70,79 @@ namespace Stormtrooper
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public MapWithSetStormtroopersGeneric<DrawningObjectStorm, AbstractMap> this[string ind]
public MapWithSetStormtroopersGeneric<IDrawningObject, AbstractMap> this[string ind]
{
get
{
if (_mapStorages.ContainsKey(ind)) return _mapStorages[ind];
return null;
}
}
/// <summary>
/// Сохранение информации по самолётам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns></returns>
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter sw = new(filename))
{
sw.WriteLine("MapsCollection");
foreach (var storage in _mapStorages)
{
sw.WriteLine($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}");
}
}
}
/// <summary>
/// Загрузка информации по самолётам в ангаре из файла
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не найден");
}
string line;
using (StreamReader sw = new(filename))
{
line = sw.ReadLine();
if (line == null || !line.Contains("MapsCollection"))
{
throw new FileFormatException("Неверный формат файла");
}
_mapStorages.Clear();
line = sw.ReadLine();
while (line != null)
{
var elem = line.Split(separatorDict);
AbstractMap map = null;
switch (elem[1])
{
case "Простая карта":
map = new SimpleMap();
break;
case "Ясное небо":
map = new SecondMap();
break;
case "Пасмурное небо":
map = new ThirdMap();
break;
}
_mapStorages.Add(elem[0], new MapWithSetStormtroopersGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
line = sw.ReadLine();
}
}
}
}
}

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"
}
}
}