This commit is contained in:
kirkorovka 2024-06-09 02:07:07 +04:00
parent 6f06ed0ff6
commit c2e139d3e3
22 changed files with 323 additions and 138 deletions

View File

@ -19,7 +19,7 @@ public abstract class AbstractCompany
protected ICollectionGenericObjects<DrawingBase>? _collection = null; protected ICollectionGenericObjects<DrawingBase>? _collection = null;
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight) - 1;
public AbstractCompany(int picWidth, int picHeigth, ICollectionGenericObjects<DrawingBase> collection) public AbstractCompany(int picWidth, int picHeigth, ICollectionGenericObjects<DrawingBase> collection)
{ {

View File

@ -1,14 +1,15 @@
using System; using Project_SelfPropelledArtilleryUnit.Exceptions;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Project_SelfPropelledArtilleryUnit.CollectionGenericObjects; namespace Project_SelfPropelledArtilleryUnit.CollectionGenericObjects;
public class ListGenericObjects<T> : ICollectionGenericObjects<T> public class ListGenericObjects<T> : ICollectionGenericObjects<T>
where T : class where T : class
{ {
private readonly List<T?> _collection; private readonly List<T?> _collection;
private int _maxCount; private int _maxCount;
public int MaxCount public int MaxCount
@ -24,7 +25,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
} }
public int Count => _collection.Count; public int Count => _collection.Count;
public CollectionType GetCollectionType => CollectionType.List; public CollectionType GetCollectionType => CollectionType.List;
@ -35,30 +36,46 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position) public T? Get(int position)
{ {
if (position < 0 || position >= _collection.Count || _collection == null || _collection.Count == 0) return null; if (position < 0 || position >= Count)
{
throw new PositionOutOfCollectionException(position);
}
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj)
{ {
if (Count == _maxCount) return -1; if (Count == _maxCount)
{
throw new CollectionOverflowException(Count);
}
_collection.Add(obj); _collection.Add(obj);
return _collection.Count; return Count;
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
if (Count == _maxCount || position < 0 || position > Count) return -1; if (Count == _maxCount)
{
throw new CollectionOverflowException(Count);
}
if (position >= Count || position < 0)
{
throw new CollectionOverflowException(Count);
}
_collection.Insert(position, obj); _collection.Insert(position, obj);
return position; return position;
} }
public T? Remove(int position) public T? Remove(int position)
{ {
if (_collection == null || position < 0 || position >= _collection.Count) return null; if (position >= Count || position < 0)
T? obj = _collection[position]; {
_collection[position] = null; throw new PositionOutOfCollectionException(position);
}
T obj = _collection[position];
_collection.RemoveAt(position);
return obj; return obj;
} }

View File

@ -1,4 +1,5 @@
using Project_SelfPropelledArtilleryUnit.Drawings; using Project_SelfPropelledArtilleryUnit.Drawings;
using Project_SelfPropelledArtilleryUnit.Exceptions;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -7,7 +8,7 @@ using System.Threading.Tasks;
namespace Project_SelfPropelledArtilleryUnit.CollectionGenericObjects; namespace Project_SelfPropelledArtilleryUnit.CollectionGenericObjects;
public class MassiveGenericObjects <T> : ICollectionGenericObjects<T> public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
where T : class where T : class
{ {
private T?[] _collection; private T?[] _collection;
@ -43,77 +44,79 @@ public class MassiveGenericObjects <T> : ICollectionGenericObjects<T>
public T? Get(int position) public T? Get(int position)
{ {
if (position < 0 || position >= Count)
if (position >= _collection.Length || position < 0)
{ {
return null; throw new PositionOutOfCollectionException(position);
} }
return _collection[position]; return _collection[position];
} }
public int Insert(T obj) public int Insert(T obj)
{ {
for (int i = 0; i < Count; i++)
int index = 0;
while (index < _collection.Length)
{ {
if (_collection[index] == null) if (_collection[i] == null)
{ {
_collection[index] = obj; _collection[i] = obj;
return index; return i;
} }
index++;
} }
return -1;
throw new CollectionOverflowException(Count);
} }
public int Insert(T obj, int position) public int Insert(T obj, int position)
{ {
if (position < 0 || position >= Count)
if (position >= _collection.Length || position < 0) {
return -1; throw new PositionOutOfCollectionException(position);
}
if (_collection[position] != null) if (_collection[position] == null)
{
_collection[position] = obj;
return position;
}
else
{ {
int nullIndex = -1;
for (int i = position + 1; i < Count; i++) for (int i = position + 1; i < Count; i++)
{ {
if (_collection[i] == null) if (_collection[i] == null)
{ {
nullIndex = i; _collection[i] = obj;
break; return i;
} }
} }
if (nullIndex < 0) for (int i = 0; i < position; i++)
{ {
return -1; if (_collection[i] == null)
} {
_collection[i] = obj;
int j = nullIndex - 1; return i;
while (j >= position) }
{
_collection[j + 1] = _collection[j];
j--;
} }
} }
_collection[position] = obj; throw new CollectionOverflowException(Count);
return position;
} }
public T? Remove(int position) public T? Remove(int position)
{ {
if (position >= _collection.Length || position < 0) if (position >= Count || position < 0)
{ {
return null; throw new PositionOutOfCollectionException(position);
}
T? obj = _collection[position];
if (obj == null)
{
throw new ObjectNotFoundException(position);
} }
T temp = _collection[position];
_collection[position] = null; _collection[position] = null;
return temp; return obj;
} }
public IEnumerable<T?> GetItems() public IEnumerable<T?> GetItems()

View File

@ -1,4 +1,5 @@
using Project_SelfPropelledArtilleryUnit.Drawings; using Project_SelfPropelledArtilleryUnit.Drawings;
using Project_SelfPropelledArtilleryUnit.Exceptions;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -15,9 +16,9 @@ internal class StorageCollection<T>
public List<string> Keys => _storages.Keys.ToList(); public List<string> Keys => _storages.Keys.ToList();
private readonly string _collectionKey = "CollectionsStorage"; private readonly string _collectionKey = "CollectionsStorage";
private readonly string _separatorForKeyValue = "|"; private readonly string _separatorForKeyValue = "|";
private readonly string _separatorItems = ";"; private readonly string _separatorItems = ";";
public StorageCollection() public StorageCollection()
@ -55,11 +56,11 @@ internal class StorageCollection<T>
} }
} }
public bool SaveData(string filename) public void SaveData(string filename)
{ {
if (_storages.Count == 0) if (_storages.Count == 0)
{ {
return false; throw new Exception("В хранилище отсутствуют коллекции для сохранения");
} }
if (File.Exists(filename)) if (File.Exists(filename))
@ -97,25 +98,25 @@ internal class StorageCollection<T>
} }
} }
} }
return true;
} }
public bool LoadData(string filename) public void LoadData(string filename)
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new FileNotFoundException("Файл не существует");
} }
using (StreamReader reader = new(filename)) using (StreamReader reader = new(filename))
{ {
string line = reader.ReadLine(); string line = reader.ReadLine();
if (line == null || line.Length == 0) if (line == null || line.Length == 0)
{ {
return false; throw new IOException("В файле нет данных");
} }
if (!line.Equals(_collectionKey)) if (!line.Equals(_collectionKey))
{ {
return false; throw new IOException("В файле неверные данные");
} }
_storages.Clear(); _storages.Clear();
while ((line = reader.ReadLine()) != null) while ((line = reader.ReadLine()) != null)
@ -129,7 +130,7 @@ internal class StorageCollection<T>
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType); ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null) if (collection == null)
{ {
return false; throw new IOException("В файле нет данных");
} }
collection.MaxCount = Convert.ToInt32(record[2]); collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
@ -139,17 +140,26 @@ internal class StorageCollection<T>
{ {
if (collection.Insert(truck) == -1) if (collection.Insert(truck) == -1)
{ {
return false; try
{
if (collection.Insert(truck) == -1)
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new Exception("Коллекция переполнена", ex);
}
} }
} }
} }
_storages.Add(record[0], collection); _storages.Add(record[0], collection);
} }
} }
return true;
} }
private static ICollectionGenericObjects<T>? private static ICollectionGenericObjects<T>?
CreateCollection(CollectionType collectionType) CreateCollection(CollectionType collectionType)
{ {

View File

@ -18,7 +18,7 @@ namespace Project_SelfPropelledArtilleryUnit.Drawings
private readonly int _drawingSAUWidth = 150; private readonly int _drawingSAUWidth = 150;
private readonly int _drawingSAUHeight = 80; private readonly int _drawingSAUHeight = 80;
public int? GetPosX => _startPosX; public int? GetPosX => _startPosX;
public int? GetPosY => _startPosY; public int? GetPosY => _startPosY;
@ -29,18 +29,18 @@ namespace Project_SelfPropelledArtilleryUnit.Drawings
public DrawingBase(int speed, double weight, Color bodyColor) : this() public DrawingBase(int speed, double weight, Color bodyColor) : this()
{ {
BaseSAU =new BaseSAU(speed, weight, bodyColor); BaseSAU = new BaseSAU(speed, weight, bodyColor);
} }
public DrawingBase() public DrawingBase()
{ {
_pictureWidth = null; _pictureWidth = null;
_pictureHeight = null; _pictureHeight = null;
_startPosX = null; _startPosX = null;
_startPosY = null; _startPosY = null;
} }
public DrawingBase(int width,int height) : this() public DrawingBase(int width, int height) : this()
{ {
_drawingSAUWidth = width; _drawingSAUWidth = width;
_drawingSAUHeight = height; _drawingSAUHeight = height;
@ -129,7 +129,7 @@ namespace Project_SelfPropelledArtilleryUnit.Drawings
if (_startPosY.Value - BaseSAU.Step > 0) if (_startPosY.Value - BaseSAU.Step > 0)
{ {
_startPosY -= (int)BaseSAU.Step; _startPosY -= (int)BaseSAU.Step;
} }
return true; return true;
case DirectionType.Right: case DirectionType.Right:
if (_startPosX.Value + BaseSAU.Step + _drawingSAUWidth < _pictureWidth.Value) if (_startPosX.Value + BaseSAU.Step + _drawingSAUWidth < _pictureWidth.Value)
@ -155,7 +155,7 @@ namespace Project_SelfPropelledArtilleryUnit.Drawings
return; return;
} }
Pen pen = new(Color.Black); Pen pen = new(Color.Black);
Brush BaseBrush = new SolidBrush(BaseSAU.BodyColor); Brush BaseBrush = new SolidBrush(BaseSAU.BodyColor);
Brush WheelBrush = new SolidBrush(Color.Brown); Brush WheelBrush = new SolidBrush(Color.Brown);
@ -186,7 +186,7 @@ namespace Project_SelfPropelledArtilleryUnit.Drawings
Point point8 = new Point(_startPosX.Value + 150, _startPosY.Value + 20); Point point8 = new Point(_startPosX.Value + 150, _startPosY.Value + 20);
Point point9 = new Point(_startPosX.Value + 100, _startPosY.Value + 35); Point point9 = new Point(_startPosX.Value + 100, _startPosY.Value + 35);
Point[] Points2 = { point6, point7, point8, point9 }; Point[] Points2 = { point6, point7, point8, point9 };
g.FillPolygon(BaseBrush, Points2); g.FillPolygon(BaseBrush, Points2);
Point point10 = new Point(_startPosX.Value + 140, _startPosY.Value + 10); Point point10 = new Point(_startPosX.Value + 140, _startPosY.Value + 10);
Point point11 = new Point(_startPosX.Value + 145, _startPosY.Value + 5); Point point11 = new Point(_startPosX.Value + 145, _startPosY.Value + 5);

View File

@ -10,12 +10,12 @@ namespace Project_SelfPropelledArtilleryUnit.Drawings;
public class DrawingSAU : DrawingBase public class DrawingSAU : DrawingBase
{ {
public DrawingSAU(int speed, double weight, Color bodyColor, Color additionalColor, bool tracks, bool guns) : base(150, 100) public DrawingSAU(int speed, double weight, Color bodyColor, Color additionalColor, bool tracks, bool guns) : base(150, 100)
{ {
BaseSAU = new EntitySAU( speed, weight, bodyColor, additionalColor, tracks, guns); BaseSAU = new EntitySAU(speed, weight, bodyColor, additionalColor, tracks, guns);
} }
public DrawingSAU(BaseSAU? baseSAU) public DrawingSAU(BaseSAU? baseSAU)
{ {
@ -27,7 +27,7 @@ public class DrawingSAU : DrawingBase
public override void DrawSAU(Graphics g) public override void DrawSAU(Graphics g)
{ {
if (BaseSAU==null || BaseSAU is not EntitySAU SAU || !_startPosX.HasValue || !_startPosY.HasValue) if (BaseSAU == null || BaseSAU is not EntitySAU SAU || !_startPosX.HasValue || !_startPosY.HasValue)
{ {
return; return;
} }
@ -55,7 +55,7 @@ public class DrawingSAU : DrawingBase
} }
} }
} }

View File

@ -11,7 +11,7 @@ public static class ExtentionDrawing
{ {
private static readonly string _separatorForObject = ":"; private static readonly string _separatorForObject = ":";
public static DrawingBase? CreateDrawningBase(this string info) public static DrawingBase? CreateDrawningBase(this string info)
{ {
string[] strs = info.Split(_separatorForObject); string[] strs = info.Split(_separatorForObject);

View File

@ -12,7 +12,7 @@ namespace Project_SelfPropelledArtilleryUnit.Entity
public double Weight { get; private set; } public double Weight { get; private set; }
public Color BodyColor { get; private set; } public Color BodyColor { get; private set; }
public double Step => Speed * 100 / Weight; public double Step => Speed * 100 / Weight;
public BaseSAU(int speed, double weight, Color bodyColor) public BaseSAU(int speed, double weight, Color bodyColor)
@ -20,7 +20,7 @@ namespace Project_SelfPropelledArtilleryUnit.Entity
Speed = speed; Speed = speed;
Weight = weight; Weight = weight;
BodyColor = bodyColor; BodyColor = bodyColor;
} }
public void SetBodyColor(Color bodyColor) public void SetBodyColor(Color bodyColor)
{ {

View File

@ -6,13 +6,13 @@ using System.Threading.Tasks;
namespace Project_SelfPropelledArtilleryUnit.Entity; namespace Project_SelfPropelledArtilleryUnit.Entity;
public class EntitySAU: BaseSAU public class EntitySAU : BaseSAU
{ {
public Color AdditionalColor { get; private set; } public Color AdditionalColor { get; private set; }
public bool Tracks { get; private set; } public bool Tracks { get; private set; }
public bool Guns { get; private set; } public bool Guns { get; private set; }
public EntitySAU(int speed, double weight, Color bodyColor, Color additionalColor, bool tracks, bool guns) : base(speed, weight, bodyColor) public EntitySAU(int speed, double weight, Color bodyColor, Color additionalColor, bool tracks, bool guns) : base(speed, weight, bodyColor)

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Project_SelfPropelledArtilleryUnit.Exceptions;
[Serializable]
internal class CollectionOverflowException : ApplicationException
{
public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: " + count) { }
public CollectionOverflowException() : base() { }
public CollectionOverflowException(string message) : base(message) { }
public CollectionOverflowException(string message, Exception exception) : base(message, exception) { }
protected CollectionOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

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

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Project_SelfPropelledArtilleryUnit.Exceptions;
[Serializable]
internal class PositionOutOfCollectionException : ApplicationException
{
public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции. Позиция " + i) { }
public PositionOutOfCollectionException() : base() { }
public PositionOutOfCollectionException(string message) : base(message) { }
public PositionOutOfCollectionException(string message, Exception exception) : base(message, exception) { }
protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -48,7 +48,7 @@ public partial class FormSAU : Form
pictureBox1.Image = bmp; pictureBox1.Image = bmp;
} }
private void Move_Click(object sender, EventArgs e) private void Move_Click(object sender, EventArgs e)
{ {
@ -81,7 +81,7 @@ public partial class FormSAU : Form
} }
} }
private void strategyStep_Click(object sender, EventArgs e) private void strategyStep_Click(object sender, EventArgs e)
{ {
@ -99,8 +99,8 @@ public partial class FormSAU : Form
1 => new MoveToBorder(), 1 => new MoveToBorder(),
_ => null, _ => null,
}; };
if (_strategy == null) if (_strategy == null)
{ {
return; return;

View File

@ -1,5 +1,9 @@
using Project_SelfPropelledArtilleryUnit.CollectionGenericObjects; using Microsoft.Extensions.Logging;
using Microsoft.VisualBasic.Logging;
using NLog;
using Project_SelfPropelledArtilleryUnit.CollectionGenericObjects;
using Project_SelfPropelledArtilleryUnit.Drawings; using Project_SelfPropelledArtilleryUnit.Drawings;
using Project_SelfPropelledArtilleryUnit.Exceptions;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
@ -10,6 +14,7 @@ using System.Runtime.InteropServices;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using ILogger = Microsoft.Extensions.Logging.ILogger;
namespace Project_SelfPropelledArtilleryUnit; namespace Project_SelfPropelledArtilleryUnit;
@ -17,10 +22,13 @@ public partial class FormSAUCollection : Form
{ {
private readonly StorageCollection<DrawingBase> _storageCollection; private readonly StorageCollection<DrawingBase> _storageCollection;
private AbstractCompany? _company = null; private AbstractCompany? _company = null;
public FormSAUCollection() private readonly ILogger _logger;
public FormSAUCollection(ILogger<FormSAUCollection> logger)
{ {
InitializeComponent(); InitializeComponent();
_storageCollection = new(); _storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма создалась");
} }
@ -40,21 +48,27 @@ public partial class FormSAUCollection : Form
form.AddEvent(SetSAU); form.AddEvent(SetSAU);
} }
private void SetSAU(DrawingBase sau) private void SetSAU(DrawingBase? sau)
{ {
if (_company == null || sau == null) try
{ {
return; if (_company == null || sau == null)
} {
return;
}
if (_company + sau != -1) if (_company + sau != -1)
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + sau.GetDataForSave());
}
} }
else catch (ObjectNotFoundException ex) { }
catch (CollectionOverflowException ex)
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
@ -71,14 +85,19 @@ public partial class FormSAUCollection : Form
} }
int pos = Convert.ToInt32(maskedTextBox.Text); int pos = Convert.ToInt32(maskedTextBox.Text);
if (_company - pos != null) try
{ {
MessageBox.Show("Объект удален"); if (_company - pos != null)
pictureBox.Image = _company.Show(); {
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
_logger.LogInformation("Удален объект по позиции " + pos);
}
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
@ -211,13 +230,16 @@ public partial class FormSAUCollection : Form
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.SaveData(saveFileDialog.FileName)) try
{ {
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
} }
@ -226,15 +248,18 @@ public partial class FormSAUCollection : Form
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storageCollection.LoadData(openFileDialog.FileName)) try
{ {
MessageBox.Show("Загрузка прошла успешно", "Реузльтат", MessageBoxButtons.OK, MessageBoxIcon.Information); _storageCollection.LoadData(openFileDialog.FileName);
UpdateListBoxItems(); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
} }
} }
UpdateListBoxItems();
} }
} }

View File

@ -15,7 +15,7 @@ namespace Project_SelfPropelledArtilleryUnit;
public partial class FormSAUConfig : Form public partial class FormSAUConfig : Form
{ {
private DrawingBase? _drawingBase; private DrawingBase? _drawingBase;
private event Action<DrawingBase>? SauDelegate; private event Action<DrawingBase>? SauDelegate;
public FormSAUConfig() public FormSAUConfig()
{ {
@ -31,7 +31,7 @@ public partial class FormSAUConfig : Form
panelPurple.MouseDown += panel_MouseDown; panelPurple.MouseDown += panel_MouseDown;
buttonCancel.Click += (sender, e) => Close(); buttonCancel.Click += (sender, e) => Close();
} }
public void AddEvent(Action<DrawingBase> sauDelegate) public void AddEvent(Action<DrawingBase> sauDelegate)

View File

@ -8,22 +8,22 @@ namespace Project_SelfPropelledArtilleryUnit.MovementStrategy;
public abstract class AbstractStrategy public abstract class AbstractStrategy
{ {
private IMoveableObject? _moveableObject; private IMoveableObject? _moveableObject;
private StrategyStatus _state = StrategyStatus.NotInit; private StrategyStatus _state = StrategyStatus.NotInit;
protected int FieldWidth { get; private set; } protected int FieldWidth { get; private set; }
protected int FieldHeight { get; private set; } protected int FieldHeight { get; private set; }
public StrategyStatus GetStatus() { return _state; } public StrategyStatus GetStatus() { return _state; }
public void SetData(IMoveableObject moveableObject, int width, int height) public void SetData(IMoveableObject moveableObject, int width, int height)
{ {
if (moveableObject == null) if (moveableObject == null)
@ -54,22 +54,22 @@ public abstract class AbstractStrategy
MoveToTarget(); MoveToTarget();
} }
protected bool MoveLeft() => MoveTo(MovementDirection.Left); protected bool MoveLeft() => MoveTo(MovementDirection.Left);
protected bool MoveRight() => MoveTo(MovementDirection.Right); protected bool MoveRight() => MoveTo(MovementDirection.Right);
protected bool MoveUp() => MoveTo(MovementDirection.Up); protected bool MoveUp() => MoveTo(MovementDirection.Up);
protected bool MoveDown() => MoveTo(MovementDirection.Down); protected bool MoveDown() => MoveTo(MovementDirection.Down);
protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectPosition; protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectPosition;
protected int? GetStep() protected int? GetStep()
{ {
if (_state != StrategyStatus.InProgress) if (_state != StrategyStatus.InProgress)
@ -81,10 +81,10 @@ public abstract class AbstractStrategy
protected abstract void MoveToTarget(); protected abstract void MoveToTarget();
protected abstract bool IsTargetDestination(); protected abstract bool IsTargetDestination();
private bool MoveTo(MovementDirection movementDirection) private bool MoveTo(MovementDirection movementDirection)
{ {
if (_state != StrategyStatus.InProgress) if (_state != StrategyStatus.InProgress)

View File

@ -9,7 +9,7 @@ namespace Project_SelfPropelledArtilleryUnit.MovementStrategy;
public interface IMoveableObject public interface IMoveableObject
{ {
ObjectParameters? GetObjectPosition { get; } ObjectParameters? GetObjectPosition { get; }

View File

@ -9,16 +9,16 @@ namespace Project_SelfPropelledArtilleryUnit.MovementStrategy;
public class MoveableSAU : IMoveableObject public class MoveableSAU : IMoveableObject
{ {
private readonly DrawingBase? _SAU = null; private readonly DrawingBase? _SAU = null;
public MoveableSAU(DrawingBase sau) public MoveableSAU(DrawingBase sau)
{ {
_SAU = sau; _SAU = sau;
} }
public ObjectParameters? GetObjectPosition public ObjectParameters? GetObjectPosition
{ {
@ -46,7 +46,7 @@ public class MoveableSAU : IMoveableObject
return _SAU.MoveSAU(GetDirectionType(direction)); return _SAU.MoveSAU(GetDirectionType(direction));
} }
private static DirectionType GetDirectionType(MovementDirection direction) private static DirectionType GetDirectionType(MovementDirection direction)
{ {
return direction switch return direction switch

View File

@ -8,7 +8,7 @@ namespace Project_SelfPropelledArtilleryUnit.MovementStrategy;
public enum MovementDirection public enum MovementDirection
{ {
Up = 1, Up = 1,
Down = 2, Down = 2,
Left = 3, Left = 3,

View File

@ -1,3 +1,8 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using System;
namespace Project_SelfPropelledArtilleryUnit namespace Project_SelfPropelledArtilleryUnit
{ {
internal static class Program internal static class Program
@ -11,7 +16,21 @@ namespace Project_SelfPropelledArtilleryUnit
// To customize application configuration such as set high DPI settings or default font, // To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new FormSAUCollection());
ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider =
services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormSAUCollection>());
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormSAUCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
} }
} }
} }

View File

@ -8,6 +8,36 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<Content Include="bin\Debug\net8.0-windows\Logs\log20240520.txt" />
<Content Include="bin\Debug\net8.0-windows\Project_SelfPropelledArtilleryUnit.deps.json" />
<Content Include="bin\Debug\net8.0-windows\Project_SelfPropelledArtilleryUnit.runtimeconfig.json" />
</ItemGroup>
<ItemGroup>
<None Include="bin\Debug\net8.0-windows\carlog-2024-05-19.log" />
<None Include="bin\Debug\net8.0-windows\carlog-2024-05-20.log" />
<None Include="bin\Debug\net8.0-windows\Microsoft.Extensions.Configuration.Abstractions.dll" />
<None Include="bin\Debug\net8.0-windows\Microsoft.Extensions.DependencyInjection.Abstractions.dll" />
<None Include="bin\Debug\net8.0-windows\Microsoft.Extensions.DependencyInjection.dll" />
<None Include="bin\Debug\net8.0-windows\Microsoft.Extensions.Logging.Abstractions.dll" />
<None Include="bin\Debug\net8.0-windows\Microsoft.Extensions.Logging.dll" />
<None Include="bin\Debug\net8.0-windows\Microsoft.Extensions.Options.dll" />
<None Include="bin\Debug\net8.0-windows\Microsoft.Extensions.Primitives.dll" />
<None Include="bin\Debug\net8.0-windows\NLog.dll" />
<None Include="bin\Debug\net8.0-windows\NLog.Extensions.Logging.dll" />
<None Include="bin\Debug\net8.0-windows\Project_SelfPropelledArtilleryUnit.dll" />
<None Include="bin\Debug\net8.0-windows\Project_SelfPropelledArtilleryUnit.exe" />
<None Include="bin\Debug\net8.0-windows\Project_SelfPropelledArtilleryUnit.pdb" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.11" />
</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,15 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true" internalLogLevel="Info">
<targets>
<target xsi:type="File" name="tofile" fileName="carlog-${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>