7 лабораторная работа, итог

This commit is contained in:
AnnZhimol 2022-11-29 17:08:22 +04:00
parent a17a1a9f2b
commit 2292bc7ee1
12 changed files with 182 additions and 43 deletions

View File

@ -1,5 +1,5 @@
MapsCollection MapsCollection
were|SimpleMap|100:100:Lime; Карта 1 (первая)|SimpleMap|100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:True:True;100:100:White:Black:False:False:False;100:100:Yellow:Black:False:False:False;100:100:Lime:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:True:True:True;100:100:White:Black:False:False:False;100:100:White:Black:True:True:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:Red;100:100:Silver:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White;100:100:White:Black:False:False:False;100:100:White;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:Silver:Black:False:False:False;100:100:White;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White:Black:False:False:False;100:100:White;100:100:White;100:100:White:Lime:False:True:True;100:100:Lime:Black:False:False:False;100:100:Red;100:100:Blue:Black:False:True:True;100:100:White:Silver:False:True:True;100:100:Fuchsia;100:100:ffff8000:ffff8000:False:False:False;100:100:Red:Lime:True:True:True;100:100:Silver:Lime:True:True:True;100:100:Fuchsia;100:100:White;100:100:Red;100:100:Lime:Silver:True:True:False;
ert4rg|SimpleMap|100:100:Red;100:100:Fuchsia:Yellow:True:True:True; Карта 2 (первая)|SimpleMap|
32e32|SecondMap|100:100:Lime:Fuchsia:True:True:False;100:100:Cyan:Cyan:False:False:True;100:100:Red:Yellow:True:True:True; Карта 3 (вторая)|SecondMap|
fdgwdf|SecondMap| Карта 4 (вторая)|SecondMap|

View File

@ -18,6 +18,5 @@ namespace Warship
Antenna = antenna; Antenna = antenna;
Missile = missile; Missile = missile;
} }
} }
} }

View File

@ -1,4 +1,5 @@
using System; using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Data; using System.Data;
@ -20,10 +21,12 @@ namespace Warship
}; };
private readonly MapsCollection _mapsCollection; private readonly MapsCollection _mapsCollection;
private readonly ILogger _logger;
public FormMapWithSetWarships() public FormMapWithSetWarships(ILogger<FormMapWithSetWarships> logger)
{ {
InitializeComponent(); InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height); _mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
comboBoxSelectorMap.Items.Clear(); comboBoxSelectorMap.Items.Clear();
foreach(var elem in _mapDict) foreach(var elem in _mapDict)
@ -62,14 +65,29 @@ namespace Warship
return; return;
} }
DrawingObjectWarship warship = new(drawingWarship); DrawingObjectWarship warship = new(drawingWarship);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + warship != -1) try
{ {
MessageBox.Show("Объект добавлен"); if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + warship != -1)
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); {
_logger.LogInformation("Новый объект добавлен");
MessageBox.Show("Объект добавлен");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
_logger.LogWarning("Не удалось добавить объект");
MessageBox.Show("Не удалось добавить объект");
}
} }
else catch (StorageOverflowException ex)
{ {
MessageBox.Show("Не удалось добавить объект"); _logger.LogWarning($"Хранилище переполнено: {ex.Message}");
MessageBox.Show($"Хранилище переполнено: {ex.Message}", "Ошибка", MessageBoxButtons.OK,MessageBoxIcon.Error);
}
catch (Exception ex)
{
_logger.LogWarning($"Неизвестная ошибка: {ex.Message}");
MessageBox.Show($"Неизвестная ошибка: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
@ -88,14 +106,24 @@ namespace Warship
return; return;
} }
int pos = Convert.ToInt32(maskedTextBoxPosition.Text); int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos !=null) try
{ {
MessageBox.Show("Объект удален"); if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); {
MessageBox.Show("Объект удален");
_logger.LogInformation($"Объект на позиции {pos} удален");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
_logger.LogWarning($"Не удалось удалить объект на позиции {pos}, так как он равен null");
MessageBox.Show("Не удалось удалить объект");
}
} }
else catch (WarshipNotFoundException ex)
{ {
MessageBox.Show("Не удалось удалить объект"); _logger.LogWarning($"Ошибка удаления: {ex.Message}");
MessageBox.Show($"Ошибка удаления: {ex.Message}");
} }
} }
@ -148,21 +176,25 @@ namespace Warship
if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxMap.Text)) if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxMap.Text))
{ {
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"При добавлении карты {0}", comboBoxSelectorMap.SelectedIndex == -1 ? "не выбрали карту" : "не указали название карты");
return; return;
} }
if (!_mapDict.ContainsKey(comboBoxSelectorMap.Text)) if (!_mapDict.ContainsKey(comboBoxSelectorMap.Text))
{ {
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Карта с названием {textBoxMap.Text} отсутствует");
return; return;
} }
listBoxMaps.Items.Clear(); listBoxMaps.Items.Clear();
_mapsCollection.AddMap(textBoxMap.Text, _mapDict[comboBoxSelectorMap.Text]); _mapsCollection.AddMap(textBoxMap.Text, _mapDict[comboBoxSelectorMap.Text]);
_logger.LogInformation($"Добавлена карта {textBoxMap.Text}");
ReloadMaps(); ReloadMaps();
} }
private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e) private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{ {
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation($"Переход на карту {listBoxMaps.SelectedItem?.ToString() ?? string.Empty}");
} }
private void ButtonDeleteMap_Click(object sender, EventArgs e) private void ButtonDeleteMap_Click(object sender, EventArgs e)
@ -175,6 +207,7 @@ namespace Warship
{ {
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty); _mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
listBoxMaps.Items.Clear(); listBoxMaps.Items.Clear();
_logger.LogInformation($"Карта {listBoxMaps.SelectedItem?.ToString() ?? string.Empty} удалена");
ReloadMaps(); ReloadMaps();
} }
} }
@ -183,13 +216,16 @@ namespace Warship
{ {
if (SaveFileDialog.ShowDialog() == DialogResult.OK) if (SaveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_mapsCollection.SaveData(SaveFileDialog.FileName)) try
{ {
MessageBox.Show("Сохранение прошло успешно!", "Результат", MessageBoxButtons.OK,MessageBoxIcon.Information); _mapsCollection.SaveData(SaveFileDialog.FileName);
_logger.LogInformation($"Сохранение данных в файл {SaveFileDialog.FileName}");
MessageBox.Show("Сохранение прошло успешно!", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
} }
else catch(Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogWarning($"Не удалось сохранить файл {SaveFileDialog.FileName}: {ex.Message}");
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
} }
@ -198,14 +234,17 @@ namespace Warship
{ {
if (OpenFileDialog.ShowDialog() == DialogResult.OK) if (OpenFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_mapsCollection.LoadData(OpenFileDialog.FileName)) try
{ {
_mapsCollection.LoadData(OpenFileDialog.FileName);
_logger.LogInformation($"Загрузка из файла {OpenFileDialog.FileName}");
MessageBox.Show("Загрузка прошла успешно!", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Загрузка прошла успешно!", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadMaps(); ReloadMaps();
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogWarning($"Не удалось загрузить файл {OpenFileDialog.FileName}: {ex.Message}");
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
} }

View File

@ -27,7 +27,7 @@ namespace Warship
PanelSilver.MouseDown += PanelColor_MouseDown; PanelSilver.MouseDown += PanelColor_MouseDown;
PanelYellow.MouseDown += PanelColor_MouseDown; PanelYellow.MouseDown += PanelColor_MouseDown;
ButtonCancel.Click += (sender, e) => Close(); ButtonCancel.Click += (sender, e) => Close();
} }
private void DrawWarship() private void DrawWarship()
{ {

View File

@ -25,7 +25,7 @@ namespace Warship
_pictureHeight = pictureHeight; _pictureHeight = pictureHeight;
} }
public bool SaveData(string filename) public void SaveData(string filename)
{ {
if (File.Exists(filename)) if (File.Exists(filename))
{ {
@ -39,21 +39,20 @@ namespace Warship
sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}"); sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}");
} }
} }
return true;
} }
public bool LoadData(string filename) public void LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new Exception("Файл не найден");
} }
using (StreamReader sr = new(filename)) using (StreamReader sr = new(filename))
{ {
string str = ""; string str = "";
if ((str = sr.ReadLine()) == null || !str.Contains("MapsCollection")) if ((str = sr.ReadLine()) == null || !str.Contains("MapsCollection"))
{ {
return false; throw new Exception("Формат данных в файле не правильный");
} }
_mapStorages.Clear(); _mapStorages.Clear();
while ((str = sr.ReadLine()) != null) while ((str = sr.ReadLine()) != null)
@ -73,7 +72,6 @@ namespace Warship
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); _mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
} }
} }
return true;
} }
public void AddMap(string name, AbstractMap map) public void AddMap(string name, AbstractMap map)

View File

@ -1,17 +1,39 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace Warship namespace Warship
{ {
internal static class Program internal static class Program
{ {
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread] [STAThread]
static void Main() static void Main()
{ {
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new FormMapWithSetWarships()); var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormMapWithSetWarships>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormMapWithSetWarships>()
.AddLogging(option =>
{
var configuration = new ConfigurationBuilder()
.AddJsonFile("E:\\ÓëÃÒÓ\\2 êóðñ\\ÐÏÏ\\PIbd-22_Zhimolostnova_A.V._Battleship._Base\\Warship\\Warship\\Serilog.json")
.Build();
var Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(Logger);
});
} }
} }
} }

View File

@ -0,0 +1,12 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": { "path": "E:\\УлГТУ\\2 курс\\РПП\\PIbd-22_Zhimolostnova_A.V._Battleship._Base\\Warship\\Warship\\bin\\Debug\\net6.0-windows\\Logs.txt" }
}
]
}
}

View File

@ -23,8 +23,8 @@ namespace Warship
public int Insert(T warship) public int Insert(T warship)
{ {
if (_places.Count + 1 >= _maxCount) if (Count >= _maxCount)
return -1; throw new StorageOverflowException(_maxCount);
_places.Insert(0, warship); _places.Insert(0, warship);
return 0; return 0;
} }
@ -32,17 +32,20 @@ namespace Warship
public int Insert(T warship, int position) public int Insert(T warship, int position)
{ {
if (position >= _maxCount || position < 0) if (position >= _maxCount || position < 0)
return -1; throw new StorageOverflowException(_maxCount);
if (_places.Count + 1 >= _maxCount)
return -1;
_places.Insert(position, warship); _places.Insert(position, warship);
return position; return position;
} }
public T Remove(int position) public T Remove(int position)
{ {
if (position >= _maxCount || position < 0) if (position < 0 || position >= Count)
{
return null; return null;
}
var obj = _places[position];
if (obj == null)
throw new WarshipNotFoundException(position);
T deleted =_places[position]; T deleted =_places[position];
_places.RemoveAt(position); _places.RemoveAt(position);

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 Warship
{
[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,31 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" 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.DependencyInjection.Abstractions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyModel" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.FileProviders.Abstractions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.FileProviders.Physical" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.FileSystemGlobbing" 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="Microsoft.Extensions.Options" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Primitives" Version="7.0.0" />
<PackageReference Include="Serilog" Version="2.12.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" />
<PackageReference Include="System.Runtime.CompilerServices.Unsafe" Version="6.0.0" />
<PackageReference Include="System.Text.Encodings.Web" Version="7.0.0" />
<PackageReference Include="System.Text.Json" Version="7.0.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>

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 Warship
{
[Serializable]
internal class WarshipNotFoundException : ApplicationException
{
public WarshipNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
public WarshipNotFoundException() : base() { }
public WarshipNotFoundException(string message) : base(message) { }
public WarshipNotFoundException(string message, Exception exception) : base(message, exception) { }
protected WarshipNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

3
fsdf.txt Normal file
View File

@ -0,0 +1,3 @@
MapsCollection
djhfjrdhfv|SimpleMap|23:10:Lime:Silver:True:True:True;100:100:Red;
rgrjthgiot|SecondMap|12:100:Red:Fuchsia:True:True:True;100:100:Lime:Fuchsia:True:True:True;100:100:Blue;