Compare commits

..

29 Commits
main ... Lab_7

Author SHA1 Message Date
0f04f98896 debug add 2023-12-16 14:23:30 +04:00
2b115c48b5 done 2023-12-08 09:19:43 +04:00
192ea364fd done 2023-12-06 20:32:42 +04:00
dec7c41aac delete dop 2023-12-06 18:32:26 +04:00
685508a162 done 2023-12-06 18:28:33 +04:00
80d8e17d1e done 2023-11-23 17:35:58 +04:00
dbace1908e done fix 2023-11-21 09:19:08 +04:00
dad5aefdd0 done 2023-11-17 17:08:35 +04:00
d8c9a506d7 done 2023-11-09 21:11:35 +04:00
9cf93e28af пробелы 2023-11-03 15:58:49 +04:00
5b720463db process delegirovanie 2023-11-01 23:19:46 +04:00
212e6b1eb6 forma done 2023-11-01 22:37:59 +04:00
699c390e25 forma 2023-11-01 13:03:53 +04:00
1505925940 result after dop 2023-10-27 09:08:32 +04:00
c5d48c32a5 result 2023-10-26 16:11:46 +04:00
04d7a840bc start 2023-10-24 19:41:05 +04:00
a14763fff5 result +- 2023-10-13 11:12:32 +04:00
b785e9b65a done fix setgeneric 2023-10-13 08:36:55 +04:00
120ac79ab3 done 2023-10-12 19:50:00 +04:00
82dcfb8d83 process dopil working 2023-10-11 19:45:04 +04:00
4f1cc8a413 process TODO not all work 2023-10-11 18:50:42 +04:00
17de16fa21 process start TODO 2023-10-11 18:05:44 +04:00
0d178bc2ee process #1 start form 2023-10-11 17:56:16 +04:00
d38494867d test 2023-10-11 16:57:02 +04:00
397e330ef0 result 2023-10-10 22:29:44 +04:00
1f834e3abf process before form 2023-10-07 15:14:04 +04:00
7b827b2468 test 2023-10-03 13:04:14 +04:00
ada566ea90 result 2023-10-03 11:59:36 +04:00
147b7ab733 тест 2023-10-02 21:09:15 +04:00
37 changed files with 3150 additions and 71 deletions

View File

@ -0,0 +1,135 @@
using DumpTruck.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace DumpTruck.MovementStrategy
{
public abstract class AbstractStrategy
{
/// <summary>
/// Перемещаемый объект
/// </summary>
private IMoveableObject? _moveableObject;
/// <summary>
/// Статус перемещения
/// </summary>
private Status _state = Status.NotInit;
/// <summary>
/// Ширина поля
/// </summary>
protected int FieldWidth { get; private set; }
/// <summary>
/// Высота поля
/// </summary>
protected int FieldHeight { get; private set; }
/// <summary>
/// Статус перемещения
/// </summary>
public Status GetStatus() { return _state; }
/// <summary>
/// Установка данных
/// </summary>
/// <param name="moveableObject">Перемещаемый объект</param>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
public void SetData(IMoveableObject moveableObject, int width, int
height)
{
if (moveableObject == null)
{
_state = Status.NotInit;
return;
}
_state = Status.InProgress;
_moveableObject = moveableObject;
FieldWidth = width;
FieldHeight = height;
}
/// <summary>
/// Шаг перемещения
/// </summary>
public void MakeStep()
{
if (_state != Status.InProgress)
{
return;
}
if (IsTargetDestinaion())
{
_state = Status.Finish;
return;
}
MoveToTarget();
}
/// <summary>
/// Перемещение влево
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveLeft() => MoveTo(DirectionType.Left);
/// <summary>
/// Перемещение вправо
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveRight() => MoveTo(DirectionType.Right);
/// <summary>
/// Перемещение вверх
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveUp() => MoveTo(DirectionType.Up);
/// <summary>
/// Перемещение вниз
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться,false - неудача)</returns>
protected bool MoveDown() => MoveTo(DirectionType.Down);
/// <summary>
/// Параметры объекта
/// </summary>
protected ObjectParameters? GetObjectParameters =>
_moveableObject?.GetObjectPosition;
/// <summary>
/// Шаг объекта
/// </summary>
/// <returns></returns>
protected int? GetStep()
{
if (_state != Status.InProgress)
{
return null;
}
return _moveableObject?.GetStep;
}
/// <summary>
/// Перемещение к цели
/// </summary>
protected abstract void MoveToTarget();
/// <summary>
/// Достигнута ли цель
/// </summary>
/// <returns></returns>
protected abstract bool IsTargetDestinaion();
/// <summary>
/// Попытка перемещения в требуемом направлении
/// </summary>
/// <param name="directionType">Направление</param>
/// <returns>Результат попытки (true - удалось переместиться, false - неудача)</returns>
private bool MoveTo(DirectionType directionType)
{
if (_state != Status.InProgress)
{
return false;
}
if (_moveableObject?.CheckCanMove(directionType) ?? false)
{
_moveableObject.MoveObject(directionType);
return true;
}
return false;
}
}
}

View File

@ -0,0 +1,147 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DumpTruck.DrawningObjects;
using DumpTruck.Entities;
using DumpTruck.MovementStrategy;
namespace DumpTruck.Generics
{
internal class CarsGenericCollection<T, U>
where T : DrawningCar
where U : IMoveableObject
{
public IEnumerable<T?> GetCars => _collection.GetCars();
/// <summary>
/// Ширина окна прорисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна прорисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Размер занимаемого объектом места (ширина)
/// </summary>
private readonly int _placeSizeWidth = 210;
/// <summary>
/// Размер занимаемого объектом места (высота)
/// </summary>
private readonly int _placeSizeHeight = 90;
/// <summary>
/// Набор объектов
/// </summary>
private readonly SetGeneric<T> _collection;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
public CarsGenericCollection(int picWidth, int picHeight)
{
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = new SetGeneric<T>(width * height);
}
/// <summary>
/// Перегрузка оператора сложения
/// </summary>
/// <param name="collect"></param>
/// <param name="obj"></param>
/// <returns></returns>
public static int operator +(CarsGenericCollection<T, U> collect, T?
obj)
{
if (obj == null)
{
return -1;
}
return collect._collection.Insert(obj);
}
/// <summary>
/// Перегрузка оператора вычитания
/// </summary>
/// <param name="collect"></param>
/// <param name="pos"></param>
/// <returns></returns>
public static T? operator -(CarsGenericCollection<T, U> collect, int
pos)
{
T? obj = collect._collection[pos];
collect._collection.Remove(pos);
return obj;
}
/// <summary>
/// Получение объекта IMoveableObject
/// </summary>
/// <param name="pos"></param>
/// <returns></returns>
public U? GetU(int pos)
{
return (U?)_collection.Get(pos)?.GetMoveableObject;
}
/// <summary>
/// Вывод всего набора объектов
/// </summary>
/// <returns></returns>
public Bitmap ShowCars()
{
Bitmap bmp = new(_pictureWidth, _pictureHeight);
Graphics gr = Graphics.FromImage(bmp);
DrawBackground(gr);
DrawObjects(gr);
return bmp;
}
/// <summary>
/// Метод отрисовки фона
/// </summary>
/// <param name="g"></param>
private void DrawBackground(Graphics g)
{
Pen pen = new(Color.Black, 3);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight +
1; ++j)
{//линия рамзетки места
g.DrawLine(pen, i * _placeSizeWidth, j *
_placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth / 2, j *
_placeSizeHeight);
}
g.DrawLine(pen, i * _placeSizeWidth, 0, i *
_placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight);
}
}
/// <summary>
/// Метод прорисовки объектов
/// </summary>
/// <param name="g"></param>
private void DrawObjects(Graphics g)
{
int numPlacesInRow = _pictureWidth / _placeSizeWidth;
int i = 0;
foreach (var car in _collection.GetCars())
{
if (car != null)
{
// TODO получение объекта
// TODO установка позиции
// TODO прорисовка объекта
car.SetPosition((i % numPlacesInRow) * _placeSizeWidth + _placeSizeWidth / 20, _placeSizeHeight * (i / numPlacesInRow) + _placeSizeHeight / 10);
car.DrawTransport(g);
}
i += 1;
}
}
}
}

View File

@ -0,0 +1,190 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DumpTruck.DrawningObjects;
using DumpTruck.MovementStrategy;
namespace DumpTruck.Generics
{
internal class CarsGenericStorage
{
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private static readonly char _separatorForKeyValue = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char _separatorRecords = ';';
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<string, CarsGenericCollection<DrawningCar,
DrawningObjectCar>> _carStorages;
/// <summary>
/// Возвращение списка названий наборов
/// </summary>
public List<string> Keys => _carStorages.Keys.ToList();
/// <summary>
/// Ширина окна отрисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна отрисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="pictureWidth"></param>
/// <param name="pictureHeight"></param>
public CarsGenericStorage(int pictureWidth, int pictureHeight)
{
_carStorages = new Dictionary<string,
CarsGenericCollection<DrawningCar, DrawningObjectCar>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
/// <summary>
/// Добавление набора
/// </summary>
/// <param name="name">Название набора</param>
public void AddSet(string name)
{
// TODO Прописать логику для добавления
_carStorages.Add(name, new CarsGenericCollection<DrawningCar, DrawningObjectCar>(_pictureWidth, _pictureHeight));
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="name">Название набора</param>
public void DelSet(string name)
{
if (!_carStorages.ContainsKey(name))
{
return;
}
_carStorages.Remove(name);
}
/// <summary>
/// Доступ к набору
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public CarsGenericCollection<DrawningCar, DrawningObjectCar>?
this[string ind]
{
get
{
if (_carStorages.ContainsKey(ind))
{
return _carStorages[ind];
}
return null;
}
}
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string,
CarsGenericCollection<DrawningCar, DrawningObjectCar>> record in _carStorages)
{
StringBuilder records = new();
foreach (DrawningCar? elem in record.Value.GetCars)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
throw new Exception("Невалиданя операция, нет данных для сохранения");
}
string toWrite = $"CarStorage{Environment.NewLine}{data}";
var strs = toWrite.Split(new char[] { '\n', '\r' },
StringSplitOptions.RemoveEmptyEntries);
using (StreamWriter sw = new(filename))
{
foreach (var str in strs)
{
sw.WriteLine(str);
}
}
return;
}
public bool LoadData(string filename)
{
{
if (!File.Exists(filename))
{
throw new IOException("Файл не найден");
}
using (StreamReader sr = new(filename))
{
string str = sr.ReadLine();
var strs = str.Split(new char[] { '\n', '\r' },
StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
throw new IOException("Нет данных для загрузки");
}
if (!strs[0].StartsWith("CarStorage"))
{
throw new IOException("Неверный формат данных");
}
_carStorages.Clear();
do
{
string[] record = str.Split(_separatorForKeyValue,
StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
str = sr.ReadLine();
continue;
}
CarsGenericCollection<DrawningCar, DrawningObjectCar>
collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords,
StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawningCar? car = elem?.CreateDrawningCar(_separatorForObject, _pictureWidth, _pictureHeight);
if (car != null)
{
if (collection + car == -1)
{
return false;
}
}
}
_carStorages.Add(record[0], collection);
str = sr.ReadLine();
} while (str != null);
}
return true;
}
}
}
}

View File

@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DumpTruck.DrawningObjects;
namespace DumpTruck
{
public delegate void CarDelegate(DrawningCar car);
}

View File

@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DumpTruck
{
public enum DirectionType
{
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}
}

View File

@ -0,0 +1,83 @@
using DumpTruck;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DumpTruck.Entities;
namespace DumpTruck.DrawningObjects
{
public class DrawningDumpTruck : DrawningCar
{
public DrawningDumpTruck(int speed, double weight, Color bodyColor, Color additionalColor, bool bodyKit, bool tent, int width, int height): base(speed, weight, bodyColor, width, height, 110, 60)
{
if (EntityCar != null)
{
EntityCar = new EntityDumpTruck(speed, weight, bodyColor,additionalColor, bodyKit, tent);
}
}
public override void DrawTransport(Graphics g)
{
if (EntityCar is not EntityDumpTruck dumpTruck)
{
return;
}
Pen pen = new Pen(Color.Black);
Brush addBrush = new SolidBrush(dumpTruck.AdditionalColor);
Brush brush = new SolidBrush(dumpTruck.BodyColor);
base.DrawTransport(g);
if (dumpTruck.Tent)
{
Point[] points = new Point[3];
points[0].X = _startPosX; points[0].Y = _startPosY + 35;
points[1].X = _startPosX + 85; points[1].Y = _startPosY;
points[2].X = _startPosX + 85; points[2].Y = _startPosY + 35;
g.FillPolygon(addBrush, points);
}
if (dumpTruck.BodyKit)
{
Point[] points = new Point[4];
points[0].X = _startPosX; points[0].Y = _startPosY + 35;
points[1].X = _startPosX; points[1].Y = _startPosY;
points[2].X = _startPosX + 85; points[2].Y = _startPosY;
points[3].X = _startPosX + 85; points[3].Y = _startPosY + 35;
g.FillPolygon(addBrush, points);
}
if (dumpTruck.BodyKit && dumpTruck.Tent)
{
int x = _startPosX;
int y = _startPosY - 8;
g.FillRectangle(brush, _startPosX, _startPosY, 95, 3);
for (int i = 0; i < 6; i++)
{
Rectangle smallRect = new Rectangle(x, y, 15, 15);
g.FillPie(brush, smallRect, 0, 180);
x += 15;
}
}
}
public void setAddColor(Color color)
{
((EntityDumpTruck)EntityCar).AdditionalColor = color;
}
}
}

View File

@ -0,0 +1,167 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DumpTruck.Entities;
using DumpTruck.MovementStrategy;
namespace DumpTruck.DrawningObjects
{
public class DrawningCar
{
public EntityCar? EntityCar { get; protected set; }
private int _pictureWidth;
private int _pictureHeight;
protected int _startPosX;
protected int _startPosY;
private readonly int _carWidth = 110;
private readonly int _carHeight = 60;
/// <summary>
/// Координата X объекта
/// </summary>
public int GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _carWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _carHeight;
/// <summary>
/// Получение объекта IMoveableObject из объекта DrawningCar
/// </summary>
public IMoveableObject GetMoveableObject => new DrawningObjectCar(this);
public DrawningCar(int speed, double weight, Color bodyColor, int width, int height)
{
if (width < _carWidth || height < _carHeight)
{
return;
}
_pictureWidth = width;
_pictureHeight = height;
EntityCar = new EntityCar(speed, weight, bodyColor);
}
protected DrawningCar(int speed, double weight, Color bodyColor, int
width, int height, int carWidth, int carHeight)
{
if (width <= _carWidth || height <= _carHeight)
{
return;
}
_pictureWidth = width;
_pictureHeight = height;
_carWidth = carWidth;
_carHeight = carHeight;
EntityCar = new EntityCar(speed, weight, bodyColor);
}
public void SetPosition(int x, int y)
{
if (x < 0 || x >= _pictureWidth || y < 0 || y >= _pictureHeight)
{
_startPosX = 0;
_startPosY = 0;
}
_startPosX = x;
_startPosY = y;
}
public void MoveTransport(DirectionType direction)
{
if (!CanMove(direction) || EntityCar == null)
{
return;
}
switch (direction)
{
//влево
case DirectionType.Left:
_startPosX -= (int)EntityCar.Step;
break;
//вверх
case DirectionType.Up:
_startPosY -= (int)EntityCar.Step;
break;
// вправо
case DirectionType.Right:
_startPosX += (int)EntityCar.Step;
break;
//вниз
case DirectionType.Down:
_startPosY += (int)EntityCar.Step;
break;
}
}
public bool CanMove(DirectionType direction)
{
if (EntityCar == null)
{
return false;
}
return direction switch
{
//влево
DirectionType.Left => _startPosX - EntityCar.Step > 0,
//вверх
DirectionType.Up => _startPosY - EntityCar.Step > 0,
// вправо
DirectionType.Right => _startPosX + EntityCar.Step + _carWidth < _pictureWidth,
//вниз
DirectionType.Down => _startPosY + EntityCar.Step + _carHeight < _pictureHeight,
_ => false,
};
}
public virtual void DrawTransport(Graphics g)
{
if (EntityCar == null)
{
return;
}
Pen pen = new Pen(Color.Black);
Brush brush = new SolidBrush(EntityCar.BodyColor);
//границы автомобиля
g.FillRectangle(brush, _startPosX, _startPosY + 35, 110, 10);
g.FillRectangle(brush, _startPosX + 85, _startPosY, 25, 35);
g.FillEllipse(brush, _startPosX, _startPosY + 35 + 10, 15, 15);
g.FillEllipse(brush, _startPosX + 15, _startPosY + 35 + 10, 15, 15);
g.FillEllipse(brush, _startPosX + 95, _startPosY + 35 + 10, 15, 15);
}
public void setColor(Color color)
{
if (EntityCar== null)
return;
EntityCar.BodyColor = color;
}
}
}

View File

@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DumpTruck.DrawningObjects;
using DumpTruck.MovementStrategy;
namespace DumpTruck.MovementStrategy
{
internal class DrawningObjectCar : IMoveableObject
{
private readonly DrawningCar? _drawningCar = null;
public DrawningObjectCar(DrawningCar drawningCar)
{
_drawningCar = drawningCar;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_drawningCar == null || _drawningCar.EntityCar ==
null)
{
return null;
}
return new ObjectParameters(_drawningCar.GetPosX,
_drawningCar.GetPosY, _drawningCar.GetWidth, _drawningCar.GetHeight);
}
}
public int GetStep => (int)(_drawningCar?.EntityCar?.Step ?? 0);
public bool CheckCanMove(DirectionType direction) =>
_drawningCar?.CanMove(direction) ?? false;
public void MoveObject(DirectionType direction) =>
_drawningCar?.MoveTransport(direction);
}
}

View File

@ -8,4 +8,38 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.5" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.5" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
</Project>

View File

@ -0,0 +1,46 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DumpTruck.Entities
{
public class EntityCar
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; set; }
/// <summary>
/// Шаг перемещения автомобиля
/// </summary>
public double Step => (double)Speed * 100 / Weight;
/// <summary>
/// Конструктор с параметрами
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Основной цвет</param>
public EntityCar(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
public void setColor(Color color)
{
BodyColor = color;
}
}
}

View File

@ -0,0 +1,51 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DumpTruck.Entities
{
public class EntityDumpTruck : EntityCar
{
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
public Color AdditionalColor { get; set; }
/// <summary>
/// Признак (опция) наличия кузова
/// </summary>
public bool BodyKit { get; private set; }
/// <summary>
/// Признак (опция) наличия tent
/// </summary>
public bool Tent { get; private set; }
public EntityDumpTruck(int speed, double weight, Color bodyColor, Color
additionalColor, bool bodyKit, bool tent) : base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
BodyKit = bodyKit;
Tent = tent;
}
public void setAddColor(Color color)
{
AdditionalColor = color;
}
}
}

View File

@ -0,0 +1,55 @@
using DumpTruck.DrawningObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DumpTruck.Entities;
namespace DumpTruck
{
public static class ExtentionDrawningCar
{
public static DrawningCar? CreateDrawningCar(this string info, char
separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawningCar(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
}
if (strs.Length == 6)
{
return new DrawningDumpTruck(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]),
Color.FromName(strs[2]),
Color.FromName(strs[3]),
Convert.ToBoolean(strs[4]),
Convert.ToBoolean(strs[5]), width, height);
}
return null;
}
public static string GetDataForSave(this DrawningCar drawningCar,
char separatorForObject)
{
var car = drawningCar.EntityCar;
if (car == null)
{
return string.Empty;
}
var str = $"{car.Speed}{separatorForObject}{car.Weight}{separatorForObject}{car.BodyColor.Name}";
if (car is not EntityDumpTruck dumpTruck)
{
return str;
}
return
$"{str}{separatorForObject}{dumpTruck.AdditionalColor.Name}" +
$"{separatorForObject}{dumpTruck.BodyKit}{separatorForObject}{dumpTruck.Tent}";
}
}
}

View File

@ -1,6 +1,6 @@
namespace DumpTruck
{
partial class Form1
partial class FormDumpTruck
{
/// <summary>
/// Required designer variable.
@ -28,12 +28,181 @@
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.button1 = new System.Windows.Forms.Button();
this.pictureBox = new System.Windows.Forms.PictureBox();
this.buttonDown = new System.Windows.Forms.Button();
this.buttonUp = new System.Windows.Forms.Button();
this.buttonRight = new System.Windows.Forms.Button();
this.buttonLeft = new System.Windows.Forms.Button();
this.buttonDumpTruck = new System.Windows.Forms.Button();
this.buttonCar = new System.Windows.Forms.Button();
this.comboBoxStrategy = new System.Windows.Forms.ComboBox();
this.buttonStep = new System.Windows.Forms.Button();
this.buttonSelectCar = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(292, 97);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(283, 192);
this.button1.TabIndex = 0;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
//
// pictureBox
//
this.pictureBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBox.Location = new System.Drawing.Point(0, 0);
this.pictureBox.Name = "pictureBox";
this.pictureBox.Size = new System.Drawing.Size(884, 461);
this.pictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pictureBox.TabIndex = 1;
this.pictureBox.TabStop = false;
//
// buttonDown
//
this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDown.BackgroundImage = global::DumpTruck.Properties.Resources.down;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.buttonDown.Location = new System.Drawing.Point(721, 367);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(59, 57);
this.buttonDown.TabIndex = 3;
this.buttonDown.UseVisualStyleBackColor = true;
this.buttonDown.Click += new System.EventHandler(this.buttonMove_Click);
//
// buttonUp
//
this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonUp.BackgroundImage = global::DumpTruck.Properties.Resources.up;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.buttonUp.Location = new System.Drawing.Point(721, 304);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(59, 57);
this.buttonUp.TabIndex = 4;
this.buttonUp.UseVisualStyleBackColor = true;
this.buttonUp.Click += new System.EventHandler(this.buttonMove_Click);
//
// buttonRight
//
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::DumpTruck.Properties.Resources.right;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.buttonRight.Location = new System.Drawing.Point(786, 367);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(59, 57);
this.buttonRight.TabIndex = 5;
this.buttonRight.UseVisualStyleBackColor = true;
this.buttonRight.Click += new System.EventHandler(this.buttonMove_Click);
//
// buttonLeft
//
this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonLeft.BackgroundImage = global::DumpTruck.Properties.Resources.left;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.buttonLeft.Location = new System.Drawing.Point(656, 367);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(59, 57);
this.buttonLeft.TabIndex = 6;
this.buttonLeft.UseVisualStyleBackColor = true;
this.buttonLeft.Click += new System.EventHandler(this.buttonMove_Click);
//
// buttonDumpTruck
//
this.buttonDumpTruck.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonDumpTruck.Location = new System.Drawing.Point(28, 385);
this.buttonDumpTruck.Name = "buttonDumpTruck";
this.buttonDumpTruck.Size = new System.Drawing.Size(225, 39);
this.buttonDumpTruck.TabIndex = 7;
this.buttonDumpTruck.Text = "Добавить самосвал ";
this.buttonDumpTruck.UseVisualStyleBackColor = true;
this.buttonDumpTruck.Click += new System.EventHandler(this.buttonDumpTruck_Click);
//
// buttonCar
//
this.buttonCar.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonCar.Location = new System.Drawing.Point(277, 385);
this.buttonCar.Name = "buttonCar";
this.buttonCar.Size = new System.Drawing.Size(225, 39);
this.buttonCar.TabIndex = 8;
this.buttonCar.Text = "Добавить грузовик";
this.buttonCar.UseVisualStyleBackColor = true;
this.buttonCar.Click += new System.EventHandler(this.button2_Click);
//
// comboBoxStrategy
//
this.comboBoxStrategy.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.comboBoxStrategy.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxStrategy.FormattingEnabled = true;
this.comboBoxStrategy.Items.AddRange(new object[] {
"К центру",
"К границе"});
this.comboBoxStrategy.Location = new System.Drawing.Point(708, 12);
this.comboBoxStrategy.Name = "comboBoxStrategy";
this.comboBoxStrategy.Size = new System.Drawing.Size(164, 23);
this.comboBoxStrategy.TabIndex = 9;
this.comboBoxStrategy.SelectedIndexChanged += new System.EventHandler(this.comboBoxStrategy_SelectedIndexChanged);
//
// buttonStep
//
this.buttonStep.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.buttonStep.Location = new System.Drawing.Point(767, 53);
this.buttonStep.Name = "buttonStep";
this.buttonStep.Size = new System.Drawing.Size(105, 26);
this.buttonStep.TabIndex = 10;
this.buttonStep.Text = "Шаг";
this.buttonStep.UseVisualStyleBackColor = true;
this.buttonStep.Click += new System.EventHandler(this.buttonStep_Click);
//
// buttonSelectCar
//
this.buttonSelectCar.Location = new System.Drawing.Point(730, 97);
this.buttonSelectCar.Name = "buttonSelectCar";
this.buttonSelectCar.Size = new System.Drawing.Size(142, 29);
this.buttonSelectCar.TabIndex = 11;
this.buttonSelectCar.Text = "Выбрать машину";
this.buttonSelectCar.UseVisualStyleBackColor = true;
this.buttonSelectCar.Click += new System.EventHandler(this.buttonSelectCar_Click);
//
// FormDumpTruck
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.ClientSize = new System.Drawing.Size(884, 461);
this.Controls.Add(this.buttonSelectCar);
this.Controls.Add(this.buttonStep);
this.Controls.Add(this.comboBoxStrategy);
this.Controls.Add(this.buttonCar);
this.Controls.Add(this.buttonDumpTruck);
this.Controls.Add(this.buttonLeft);
this.Controls.Add(this.buttonRight);
this.Controls.Add(this.buttonUp);
this.Controls.Add(this.buttonDown);
this.Controls.Add(this.pictureBox);
this.Controls.Add(this.button1);
this.Name = "FormDumpTruck";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Form1";
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Button button1;
private PictureBox pictureBox;
private Button buttonDown;
private Button buttonUp;
private Button buttonRight;
private Button buttonLeft;
private Button buttonDumpTruck;
private Button buttonCar;
private ComboBox comboBoxStrategy;
private Button buttonStep;
private Button buttonSelectCar;
}
}

View File

@ -1,10 +1,163 @@
using DumpTruck.DrawningObjects;
using DumpTruck.MovementStrategy;
namespace DumpTruck
{
public partial class Form1 : Form
public partial class FormDumpTruck : Form
{
public Form1()
private DrawningCar? _drawningCar;
private AbstractStrategy? _abstractStrategy;
private AbstractStrategy? _strategy;
public DrawningCar? SelectedCar { get; private set; }
public FormDumpTruck()
{
InitializeComponent();
_strategy = null;
SelectedCar = null;
}
private void button_Click(object sender, EventArgs e)
{
}
private void Draw()
{
if (_drawningCar == null)
{
return;
}
Bitmap bmp = new Bitmap(pictureBox.Width, pictureBox.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningCar.DrawTransport(gr);
pictureBox.Image = bmp;
}
private void buttonMove_Click(object sender, EventArgs e)
{
if (_drawningCar == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
switch (name)
{
case "buttonUp":
_drawningCar.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
_drawningCar.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
_drawningCar.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
_drawningCar.MoveTransport(DirectionType.Right);
break;
}
Draw();
}
private void button2_Click(object sender, EventArgs e)
{
Random random = new();
Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
Color dopColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
_drawningCar = new DrawningCar(random.Next(100, 300),
random.Next(1000, 3000),
color,
pictureBox.Width, pictureBox.Height);
_drawningCar.SetPosition(random.Next(10, 100), random.Next(10,
100));
Draw();
}
private void buttonDumpTruck_Click(object sender, EventArgs e)
{
Random random = new();
Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
Color dopColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
if (dialog.ShowDialog() == DialogResult.OK)
{
dopColor = dialog.Color;
}
_drawningCar = new DrawningDumpTruck(random.Next(100, 300),
random.Next(1000, 3000),
color,
dopColor,
Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)),
pictureBox.Width, pictureBox.Height);
_drawningCar.SetPosition(random.Next(10, 100), random.Next(10,
100));
Draw();
}
private void buttonStep_Click(object sender, EventArgs e)
{
if (_drawningCar == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_abstractStrategy = comboBoxStrategy.SelectedIndex
switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(new
DrawningObjectCar(_drawningCar), pictureBox.Width,
pictureBox.Height);
comboBoxStrategy.Enabled = false;
}
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_abstractStrategy = null;
}
}
private void comboBoxStrategy_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void buttonSelectCar_Click(object sender, EventArgs e)
{
SelectedCar = _drawningCar;
DialogResult = DialogResult.OK;
}
}
}
}

View File

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

View File

@ -0,0 +1,258 @@
namespace DumpTruck
{
partial class FormCarCollection
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.pictureBoxCollection = new System.Windows.Forms.PictureBox();
this.panelCollection = new System.Windows.Forms.Panel();
this.ButtonRefreshCollection = new System.Windows.Forms.Button();
this.panel1 = new System.Windows.Forms.Panel();
this.maskedTextBoxNumber = new System.Windows.Forms.MaskedTextBox();
this.ButtonRemoveCar = new System.Windows.Forms.Button();
this.ButtonAddCar = new System.Windows.Forms.Button();
this.panelObjects = new System.Windows.Forms.Panel();
this.ButtonDelObject_ = new System.Windows.Forms.Button();
this.textBoxStorageName = new System.Windows.Forms.TextBox();
this.listBoxStorages = new System.Windows.Forms.ListBox();
this.ButtonAddObject = new System.Windows.Forms.Button();
this.menuStrip = new System.Windows.Forms.MenuStrip();
this.файлToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.LoadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.SaveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).BeginInit();
this.panelCollection.SuspendLayout();
this.panel1.SuspendLayout();
this.panelObjects.SuspendLayout();
this.menuStrip.SuspendLayout();
this.SuspendLayout();
//
// pictureBoxCollection
//
this.pictureBoxCollection.Location = new System.Drawing.Point(0, 27);
this.pictureBoxCollection.Name = "pictureBoxCollection";
this.pictureBoxCollection.Size = new System.Drawing.Size(630, 455);
this.pictureBoxCollection.TabIndex = 0;
this.pictureBoxCollection.TabStop = false;
//
// panelCollection
//
this.panelCollection.Controls.Add(this.ButtonRefreshCollection);
this.panelCollection.Controls.Add(this.panel1);
this.panelCollection.Controls.Add(this.panelObjects);
this.panelCollection.Location = new System.Drawing.Point(636, 0);
this.panelCollection.Name = "panelCollection";
this.panelCollection.Size = new System.Drawing.Size(217, 470);
this.panelCollection.TabIndex = 1;
//
// ButtonRefreshCollection
//
this.ButtonRefreshCollection.Location = new System.Drawing.Point(20, 414);
this.ButtonRefreshCollection.Name = "ButtonRefreshCollection";
this.ButtonRefreshCollection.Size = new System.Drawing.Size(181, 41);
this.ButtonRefreshCollection.TabIndex = 1;
this.ButtonRefreshCollection.Text = "Обновить коллекцию";
this.ButtonRefreshCollection.UseVisualStyleBackColor = true;
this.ButtonRefreshCollection.Click += new System.EventHandler(this.ButtonRefreshCollection_Click);
//
// panel1
//
this.panel1.Controls.Add(this.maskedTextBoxNumber);
this.panel1.Controls.Add(this.ButtonRemoveCar);
this.panel1.Controls.Add(this.ButtonAddCar);
this.panel1.Location = new System.Drawing.Point(17, 265);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(187, 128);
this.panel1.TabIndex = 3;
//
// maskedTextBoxNumber
//
this.maskedTextBoxNumber.Location = new System.Drawing.Point(3, 50);
this.maskedTextBoxNumber.Name = "maskedTextBoxNumber";
this.maskedTextBoxNumber.Size = new System.Drawing.Size(181, 23);
this.maskedTextBoxNumber.TabIndex = 2;
this.maskedTextBoxNumber.MaskInputRejected += new System.Windows.Forms.MaskInputRejectedEventHandler(this.maskedTextBoxNumber_MaskInputRejected);
//
// ButtonRemoveCar
//
this.ButtonRemoveCar.Location = new System.Drawing.Point(3, 79);
this.ButtonRemoveCar.Name = "ButtonRemoveCar";
this.ButtonRemoveCar.Size = new System.Drawing.Size(181, 41);
this.ButtonRemoveCar.TabIndex = 2;
this.ButtonRemoveCar.Text = "Удалить машину";
this.ButtonRemoveCar.UseVisualStyleBackColor = true;
this.ButtonRemoveCar.Click += new System.EventHandler(this.ButtonRemoveCar_Click);
//
// ButtonAddCar
//
this.ButtonAddCar.Location = new System.Drawing.Point(3, 3);
this.ButtonAddCar.Name = "ButtonAddCar";
this.ButtonAddCar.Size = new System.Drawing.Size(181, 41);
this.ButtonAddCar.TabIndex = 0;
this.ButtonAddCar.Text = "Добавить машину";
this.ButtonAddCar.UseVisualStyleBackColor = true;
this.ButtonAddCar.Click += new System.EventHandler(this.ButtonAddCar_Click);
//
// panelObjects
//
this.panelObjects.Controls.Add(this.ButtonDelObject_);
this.panelObjects.Controls.Add(this.textBoxStorageName);
this.panelObjects.Controls.Add(this.listBoxStorages);
this.panelObjects.Controls.Add(this.ButtonAddObject);
this.panelObjects.Location = new System.Drawing.Point(17, 3);
this.panelObjects.Name = "panelObjects";
this.panelObjects.Size = new System.Drawing.Size(187, 241);
this.panelObjects.TabIndex = 4;
//
// ButtonDelObject_
//
this.ButtonDelObject_.Location = new System.Drawing.Point(3, 194);
this.ButtonDelObject_.Name = "ButtonDelObject_";
this.ButtonDelObject_.Size = new System.Drawing.Size(181, 41);
this.ButtonDelObject_.TabIndex = 3;
this.ButtonDelObject_.Text = "Удалить набор";
this.ButtonDelObject_.UseVisualStyleBackColor = true;
this.ButtonDelObject_.Click += new System.EventHandler(this.ButtonDelObject__Click);
//
// textBoxStorageName
//
this.textBoxStorageName.Location = new System.Drawing.Point(3, 12);
this.textBoxStorageName.Name = "textBoxStorageName";
this.textBoxStorageName.Size = new System.Drawing.Size(181, 23);
this.textBoxStorageName.TabIndex = 3;
this.textBoxStorageName.TextChanged += new System.EventHandler(this.textBoxStorageName_TextChanged);
//
// listBoxStorages
//
this.listBoxStorages.FormattingEnabled = true;
this.listBoxStorages.ItemHeight = 15;
this.listBoxStorages.Location = new System.Drawing.Point(3, 109);
this.listBoxStorages.Name = "listBoxStorages";
this.listBoxStorages.Size = new System.Drawing.Size(181, 79);
this.listBoxStorages.TabIndex = 2;
this.listBoxStorages.SelectedIndexChanged += new System.EventHandler(this.ListBoxObjects_SelectedIndexChanged);
//
// ButtonAddObject
//
this.ButtonAddObject.Location = new System.Drawing.Point(3, 41);
this.ButtonAddObject.Name = "ButtonAddObject";
this.ButtonAddObject.Size = new System.Drawing.Size(181, 41);
this.ButtonAddObject.TabIndex = 1;
this.ButtonAddObject.Text = "Добавить набор";
this.ButtonAddObject.UseVisualStyleBackColor = true;
this.ButtonAddObject.Click += new System.EventHandler(this.ButtonAddObject_Click);
//
// menuStrip
//
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.файлToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(848, 24);
this.menuStrip.TabIndex = 2;
this.menuStrip.Text = "Файл";
//
// файлToolStripMenuItem
//
this.файлToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.LoadToolStripMenuItem,
this.SaveToolStripMenuItem});
this.файлToolStripMenuItem.Name = айлToolStripMenuItem";
this.файлToolStripMenuItem.Size = new System.Drawing.Size(48, 20);
this.файлToolStripMenuItem.Text = "Файл";
//
// LoadToolStripMenuItem
//
this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.LoadToolStripMenuItem.Text = "Загрузка";
this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
// SaveToolStripMenuItem
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.SaveToolStripMenuItem.Text = "Сохранение";
this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// openFileDialog
//
this.openFileDialog.FileName = "openFileDialog1";
this.openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
this.saveFileDialog.Filter = "txt file | *.txt";
//
// FormCarCollection
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(848, 482);
this.Controls.Add(this.panelCollection);
this.Controls.Add(this.pictureBoxCollection);
this.Controls.Add(this.menuStrip);
this.MainMenuStrip = this.menuStrip;
this.Name = "FormCarCollection";
this.Text = "Набор грузовиков";
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).EndInit();
this.panelCollection.ResumeLayout(false);
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.panelObjects.ResumeLayout(false);
this.panelObjects.PerformLayout();
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private PictureBox pictureBoxCollection;
private Panel panelCollection;
private Button ButtonAddCar;
private MaskedTextBox maskedTextBoxNumber;
private Button ButtonRemoveCar;
private Button ButtonRefreshCollection;
private Panel panelObjects;
private ListBox listBoxStorages;
private Button ButtonAddObject;
private Panel panel1;
private Button ButtonDelObject_;
private TextBox textBoxStorageName;
private MenuStrip menuStrip;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
}
}

View File

@ -0,0 +1,244 @@
using DumpTruck.DrawningObjects;
using DumpTruck.Generics;
using DumpTruck.MovementStrategy;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DumpTruck.MovementStrategy;
using DumpTruck.DrawningObjects;
using DumpTruck.Generics;
using Microsoft.Extensions.Logging;
using DumpTruck.Exceptions;
using System.Xml.Linq;
using Serilog;
namespace DumpTruck
{
public partial class FormCarCollection : Form
{
private readonly CarsGenericStorage _storage;
public FormCarCollection()
{
InitializeComponent();
_storage = new CarsGenericStorage(pictureBoxCollection.Width,
pictureBoxCollection.Height);
}
private void ReloadObjects()
{
int index = listBoxStorages.SelectedIndex;
listBoxStorages.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++)
{
listBoxStorages.Items.Add(_storage.Keys[i]);
}
if (listBoxStorages.Items.Count > 0 && (index == -1 || index
>= listBoxStorages.Items.Count))
{
listBoxStorages.SelectedIndex = 0;
}
else if (listBoxStorages.Items.Count > 0 && index > -1 &&
index < listBoxStorages.Items.Count)
{
listBoxStorages.SelectedIndex = index;
}
}
private void ButtonAddCar_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
FormCarConfig form = new FormCarConfig();
form.Show();
Action<DrawningCar>? carDelegate = new((m) =>
{
try
{
int q = obj + m;
MessageBox.Show("Объект добавлен");
Log.Information($"Добавлен объект в коллекцию {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
pictureBoxCollection.Image = obj.ShowCars();
}
catch (StorageOverflowException ex)
{
Log.Warning($"Коллекция {listBoxStorages.SelectedItem.ToString() ?? string.Empty} переполнена");
MessageBox.Show(ex.Message);
}
});
form.AddEvent(carDelegate);
}
private void ButtonRemoveCar_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
try
{
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
var q = obj - pos;
MessageBox.Show("Объект удален");
Log.Information($"Удален объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty} по номеру {pos}");
pictureBoxCollection.Image = obj.ShowCars();
}
catch (TruckNotFoundException ex)
{
Log.Warning($"Не получилось удалить объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
MessageBox.Show(ex.Message);
}
catch (FormatException ex)
{
Log.Warning($"Было введено не число");
MessageBox.Show("Введите число");
}
}
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
pictureBoxCollection.Image = obj.ShowCars();
}
private void maskedTextBoxNumber_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
{
}
private void ButtonAddObject_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxStorageName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
Log.Information($"Добавлен набор: {textBoxStorageName.Text}");
}
private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBoxCollection.Image =
_storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowCars();
}
private void ButtonDelObject__Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
if (MessageBox.Show($"Удалить объект { listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes)
{
string name = listBoxStorages.SelectedItem.ToString()
?? string.Empty;
_storage.DelSet(name);
ReloadObjects();
Log.Information($"Удален набор: {name}");
}
}
private void textBoxStorageName_TextChanged(object sender, EventArgs e)
{
}
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
Log.Information($"Файл {saveFileDialog.FileName} успешно сохранен");
}
catch (Exception ex)
{
Log.Warning("Не удалось сохранить");
MessageBox.Show($"Не сохранилось: {ex.Message}",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
Log.Information($"Файл {openFileDialog.FileName} успешно загружен");
foreach (var collection in _storage.Keys)
{
listBoxStorages.Items.Add(collection);
}
ReloadObjects();
}
catch (Exception ex)
{
Log.Warning("Не удалось загрузить");
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}

View File

@ -0,0 +1,69 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<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>125, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>265, 17</value>
</metadata>
</root>

View File

@ -0,0 +1,390 @@
namespace DumpTruck
{
partial class FormCarConfig
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.groupBoxParameters = new System.Windows.Forms.GroupBox();
this.labelAdvancedObject = new System.Windows.Forms.Label();
this.labelBaseObject = new System.Windows.Forms.Label();
this.groupBoxColors = new System.Windows.Forms.GroupBox();
this.panelWhite = new System.Windows.Forms.Panel();
this.panelPurple = new System.Windows.Forms.Panel();
this.panelLightBlue = new System.Windows.Forms.Panel();
this.panelYellow = new System.Windows.Forms.Panel();
this.panelBlue = new System.Windows.Forms.Panel();
this.panelBlack = new System.Windows.Forms.Panel();
this.panelOrange = new System.Windows.Forms.Panel();
this.panelRed = new System.Windows.Forms.Panel();
this.checkBoxTent = new System.Windows.Forms.CheckBox();
this.checkBoxKit = new System.Windows.Forms.CheckBox();
this.numericUpDownWeight = new System.Windows.Forms.NumericUpDown();
this.numericUpDownSpeed = new System.Windows.Forms.NumericUpDown();
this.labelWeight = new System.Windows.Forms.Label();
this.labelSpeed = new System.Windows.Forms.Label();
this.pictureBoxObject = new System.Windows.Forms.PictureBox();
this.panelObject = new System.Windows.Forms.Panel();
this.labelColor = new System.Windows.Forms.Label();
this.labelAddColor = new System.Windows.Forms.Label();
this.buttonAdd = new System.Windows.Forms.Button();
this.buttonCanel = new System.Windows.Forms.Button();
this.groupBoxParameters.SuspendLayout();
this.groupBoxColors.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).BeginInit();
this.panelObject.SuspendLayout();
this.SuspendLayout();
//
// groupBoxParameters
//
this.groupBoxParameters.Controls.Add(this.labelAdvancedObject);
this.groupBoxParameters.Controls.Add(this.labelBaseObject);
this.groupBoxParameters.Controls.Add(this.groupBoxColors);
this.groupBoxParameters.Controls.Add(this.checkBoxTent);
this.groupBoxParameters.Controls.Add(this.checkBoxKit);
this.groupBoxParameters.Controls.Add(this.numericUpDownWeight);
this.groupBoxParameters.Controls.Add(this.numericUpDownSpeed);
this.groupBoxParameters.Controls.Add(this.labelWeight);
this.groupBoxParameters.Controls.Add(this.labelSpeed);
this.groupBoxParameters.Location = new System.Drawing.Point(12, 12);
this.groupBoxParameters.Name = "groupBoxParameters";
this.groupBoxParameters.Size = new System.Drawing.Size(589, 328);
this.groupBoxParameters.TabIndex = 0;
this.groupBoxParameters.TabStop = false;
this.groupBoxParameters.Text = "Параметры";
//
// labelAdvancedObject
//
this.labelAdvancedObject.AllowDrop = true;
this.labelAdvancedObject.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelAdvancedObject.Location = new System.Drawing.Point(406, 271);
this.labelAdvancedObject.Name = "labelAdvancedObject";
this.labelAdvancedObject.Size = new System.Drawing.Size(98, 35);
this.labelAdvancedObject.TabIndex = 6;
this.labelAdvancedObject.Text = "Продвинутый";
this.labelAdvancedObject.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelAdvancedObject.MouseDown += new System.Windows.Forms.MouseEventHandler(this.LabelObject_MouseDown);
//
// labelBaseObject
//
this.labelBaseObject.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelBaseObject.Location = new System.Drawing.Point(295, 271);
this.labelBaseObject.Name = "labelBaseObject";
this.labelBaseObject.Size = new System.Drawing.Size(98, 35);
this.labelBaseObject.TabIndex = 2;
this.labelBaseObject.Text = "Простой";
this.labelBaseObject.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelBaseObject.MouseDown += new System.Windows.Forms.MouseEventHandler(this.LabelObject_MouseDown);
//
// groupBoxColors
//
this.groupBoxColors.Controls.Add(this.panelWhite);
this.groupBoxColors.Controls.Add(this.panelPurple);
this.groupBoxColors.Controls.Add(this.panelLightBlue);
this.groupBoxColors.Controls.Add(this.panelYellow);
this.groupBoxColors.Controls.Add(this.panelBlue);
this.groupBoxColors.Controls.Add(this.panelBlack);
this.groupBoxColors.Controls.Add(this.panelOrange);
this.groupBoxColors.Controls.Add(this.panelRed);
this.groupBoxColors.Location = new System.Drawing.Point(250, 22);
this.groupBoxColors.Name = "groupBoxColors";
this.groupBoxColors.Size = new System.Drawing.Size(303, 246);
this.groupBoxColors.TabIndex = 1;
this.groupBoxColors.TabStop = false;
this.groupBoxColors.Text = "Цвета";
//
// panelWhite
//
this.panelWhite.AllowDrop = true;
this.panelWhite.BackColor = System.Drawing.Color.White;
this.panelWhite.Location = new System.Drawing.Point(230, 106);
this.panelWhite.Name = "panelWhite";
this.panelWhite.Size = new System.Drawing.Size(57, 53);
this.panelWhite.TabIndex = 1;
//
// panelPurple
//
this.panelPurple.AllowDrop = true;
this.panelPurple.BackColor = System.Drawing.Color.Fuchsia;
this.panelPurple.Location = new System.Drawing.Point(156, 106);
this.panelPurple.Name = "panelPurple";
this.panelPurple.Size = new System.Drawing.Size(57, 53);
this.panelPurple.TabIndex = 1;
//
// panelLightBlue
//
this.panelLightBlue.AllowDrop = true;
this.panelLightBlue.BackColor = System.Drawing.Color.Cyan;
this.panelLightBlue.Location = new System.Drawing.Point(13, 106);
this.panelLightBlue.Name = "panelLightBlue";
this.panelLightBlue.Size = new System.Drawing.Size(57, 53);
this.panelLightBlue.TabIndex = 1;
//
// panelYellow
//
this.panelYellow.AllowDrop = true;
this.panelYellow.BackColor = System.Drawing.Color.Yellow;
this.panelYellow.Location = new System.Drawing.Point(156, 35);
this.panelYellow.Name = "panelYellow";
this.panelYellow.Size = new System.Drawing.Size(57, 53);
this.panelYellow.TabIndex = 1;
//
// panelBlue
//
this.panelBlue.AllowDrop = true;
this.panelBlue.BackColor = System.Drawing.Color.Blue;
this.panelBlue.Location = new System.Drawing.Point(86, 106);
this.panelBlue.Name = "panelBlue";
this.panelBlue.Size = new System.Drawing.Size(57, 53);
this.panelBlue.TabIndex = 1;
//
// panelBlack
//
this.panelBlack.AllowDrop = true;
this.panelBlack.BackColor = System.Drawing.Color.Black;
this.panelBlack.Location = new System.Drawing.Point(230, 35);
this.panelBlack.Name = "panelBlack";
this.panelBlack.Size = new System.Drawing.Size(57, 53);
this.panelBlack.TabIndex = 1;
//
// panelOrange
//
this.panelOrange.AllowDrop = true;
this.panelOrange.BackColor = System.Drawing.Color.Orange;
this.panelOrange.Location = new System.Drawing.Point(86, 35);
this.panelOrange.Name = "panelOrange";
this.panelOrange.Size = new System.Drawing.Size(57, 53);
this.panelOrange.TabIndex = 1;
//
// panelRed
//
this.panelRed.AllowDrop = true;
this.panelRed.BackColor = System.Drawing.Color.Red;
this.panelRed.Location = new System.Drawing.Point(13, 35);
this.panelRed.Name = "panelRed";
this.panelRed.Size = new System.Drawing.Size(57, 53);
this.panelRed.TabIndex = 0;
//
// checkBoxTent
//
this.checkBoxTent.AutoSize = true;
this.checkBoxTent.Location = new System.Drawing.Point(18, 164);
this.checkBoxTent.Name = "checkBoxTent";
this.checkBoxTent.Size = new System.Drawing.Size(155, 19);
this.checkBoxTent.TabIndex = 1;
this.checkBoxTent.Text = "Признак наличия тента";
this.checkBoxTent.UseVisualStyleBackColor = true;
//
// checkBoxKit
//
this.checkBoxKit.AutoSize = true;
this.checkBoxKit.Location = new System.Drawing.Point(18, 139);
this.checkBoxKit.Name = "checkBoxKit";
this.checkBoxKit.Size = new System.Drawing.Size(162, 19);
this.checkBoxKit.TabIndex = 4;
this.checkBoxKit.Text = "Признак наличия кузова";
this.checkBoxKit.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
this.numericUpDownWeight.Location = new System.Drawing.Point(88, 87);
this.numericUpDownWeight.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.numericUpDownWeight.Minimum = new decimal(new int[] {
100,
0,
0,
0});
this.numericUpDownWeight.Name = "numericUpDownWeight";
this.numericUpDownWeight.Size = new System.Drawing.Size(120, 23);
this.numericUpDownWeight.TabIndex = 3;
this.numericUpDownWeight.Value = new decimal(new int[] {
100,
0,
0,
0});
//
// numericUpDownSpeed
//
this.numericUpDownSpeed.Location = new System.Drawing.Point(88, 44);
this.numericUpDownSpeed.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.numericUpDownSpeed.Minimum = new decimal(new int[] {
100,
0,
0,
0});
this.numericUpDownSpeed.Name = "numericUpDownSpeed";
this.numericUpDownSpeed.Size = new System.Drawing.Size(120, 23);
this.numericUpDownSpeed.TabIndex = 1;
this.numericUpDownSpeed.Value = new decimal(new int[] {
100,
0,
0,
0});
//
// labelWeight
//
this.labelWeight.AutoSize = true;
this.labelWeight.Location = new System.Drawing.Point(18, 87);
this.labelWeight.Name = "labelWeight";
this.labelWeight.Size = new System.Drawing.Size(29, 15);
this.labelWeight.TabIndex = 2;
this.labelWeight.Text = "Вес:";
//
// labelSpeed
//
this.labelSpeed.AutoSize = true;
this.labelSpeed.Location = new System.Drawing.Point(18, 44);
this.labelSpeed.Name = "labelSpeed";
this.labelSpeed.Size = new System.Drawing.Size(62, 15);
this.labelSpeed.TabIndex = 1;
this.labelSpeed.Text = "Скорость:";
//
// pictureBoxObject
//
this.pictureBoxObject.Location = new System.Drawing.Point(16, 64);
this.pictureBoxObject.Name = "pictureBoxObject";
this.pictureBoxObject.Size = new System.Drawing.Size(260, 183);
this.pictureBoxObject.TabIndex = 7;
this.pictureBoxObject.TabStop = false;
//
// panelObject
//
this.panelObject.AllowDrop = true;
this.panelObject.Controls.Add(this.labelColor);
this.panelObject.Controls.Add(this.labelAddColor);
this.panelObject.Controls.Add(this.pictureBoxObject);
this.panelObject.Location = new System.Drawing.Point(618, 21);
this.panelObject.Name = "panelObject";
this.panelObject.Size = new System.Drawing.Size(294, 270);
this.panelObject.TabIndex = 2;
this.panelObject.DragDrop += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragDrop);
this.panelObject.DragEnter += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragEnter);
//
// labelColor
//
this.labelColor.AllowDrop = true;
this.labelColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelColor.Location = new System.Drawing.Point(16, 23);
this.labelColor.Name = "labelColor";
this.labelColor.Size = new System.Drawing.Size(124, 35);
this.labelColor.TabIndex = 10;
this.labelColor.Text = "Цвет";
this.labelColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.LabelColor_DragDrop);
this.labelColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.LabelColor_DragEnter);
//
// labelAddColor
//
this.labelAddColor.AllowDrop = true;
this.labelAddColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelAddColor.Location = new System.Drawing.Point(150, 23);
this.labelAddColor.Name = "labelAddColor";
this.labelAddColor.Size = new System.Drawing.Size(126, 35);
this.labelAddColor.TabIndex = 9;
this.labelAddColor.Text = "Доп. цвет";
this.labelAddColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelAddColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.LabelAddColor_DragDrop);
this.labelAddColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.LabelColor_DragEnter);
//
// buttonAdd
//
this.buttonAdd.Location = new System.Drawing.Point(672, 302);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(86, 38);
this.buttonAdd.TabIndex = 3;
this.buttonAdd.Text = "Добавить";
this.buttonAdd.UseVisualStyleBackColor = true;
this.buttonAdd.Click += new System.EventHandler(this.buttonAdd_Click);
//
// buttonCanel
//
this.buttonCanel.Location = new System.Drawing.Point(768, 302);
this.buttonCanel.Name = "buttonCanel";
this.buttonCanel.Size = new System.Drawing.Size(86, 38);
this.buttonCanel.TabIndex = 4;
this.buttonCanel.Text = "Отмена";
this.buttonCanel.UseVisualStyleBackColor = true;
//
// FormCarConfig
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(924, 348);
this.Controls.Add(this.buttonCanel);
this.Controls.Add(this.buttonAdd);
this.Controls.Add(this.panelObject);
this.Controls.Add(this.groupBoxParameters);
this.Name = "FormCarConfig";
this.Text = "FormCarConfig";
this.groupBoxParameters.ResumeLayout(false);
this.groupBoxParameters.PerformLayout();
this.groupBoxColors.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).EndInit();
this.panelObject.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private GroupBox groupBoxParameters;
private Label labelBaseObject;
private CheckBox checkBoxTent;
private CheckBox checkBoxKit;
private NumericUpDown numericUpDownWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelWeight;
private Label labelSpeed;
private GroupBox groupBoxColors;
private Panel panelWhite;
private Panel panelPurple;
private Panel panelLightBlue;
private Panel panelYellow;
private Panel panelBlue;
private Panel panelBlack;
private Panel panelOrange;
private Panel panelRed;
private PictureBox pictureBoxObject;
private Panel panelObject;
private Button buttonAdd;
private Button buttonCanel;
private Label labelAdvancedObject;
private Label labelColor;
private Label labelAddColor;
}
}

View File

@ -0,0 +1,148 @@
using DumpTruck.DrawningObjects;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DumpTruck
{
public partial class FormCarConfig : Form
{
DrawningCar? _car = null;
public event Action<DrawningCar>? EventAddCar;
public FormCarConfig()
{
InitializeComponent();
panelBlack.MouseDown += PanelColor_MouseDown;
panelPurple.MouseDown += PanelColor_MouseDown;
panelOrange.MouseDown += PanelColor_MouseDown;
panelLightBlue.MouseDown += PanelColor_MouseDown;
panelWhite.MouseDown += PanelColor_MouseDown;
panelYellow.MouseDown += PanelColor_MouseDown;
panelBlue.MouseDown += PanelColor_MouseDown;
panelRed.MouseDown += PanelColor_MouseDown;
buttonCanel.Click += (s, e) => Close();
}
private void DrawCar()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_car?.SetPosition(5, 5);
_car?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
private void PanelColor_MouseDown(object sender, MouseEventArgs e)
{
(sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor,
DragDropEffects.Move | DragDropEffects.Copy);
}
private void LabelColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)))
e.Effect = DragDropEffects.Copy;
else
{
e.Effect = DragDropEffects.None;
}
}
private void LabelColor_DragDrop(object sender, DragEventArgs e)
{
if (_car is DrawningCar car)
{
labelColor.BackColor = (Color)e.Data.GetData(typeof(Color));
_car.setColor(labelColor.BackColor);
}
DrawCar();
}
private void LabelAddColor_DragDrop(object sender, DragEventArgs e)
{
if (_car is DrawningDumpTruck car)
{
labelAddColor.BackColor = (Color)e.Data.GetData(typeof(Color));
((DrawningDumpTruck)_car).setAddColor(labelAddColor.BackColor);
}
DrawCar();
}
private void LabelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label)?.DoDragDrop((sender as Label)?.Name,
DragDropEffects.Move | DragDropEffects.Copy);
}
private void PanelObject_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(DataFormats.Text) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void PanelObject_DragDrop(object sender, DragEventArgs e)
{
switch (e.Data?.GetData(DataFormats.Text).ToString())
{
case "labelBaseObject":
_car = new DrawningCar((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, pictureBoxObject.Width,
pictureBoxObject.Height);
labelColor.BackColor = Color.White;
labelAddColor.BackColor = Color.Transparent;
break;
case "labelAdvancedObject":
_car = new DrawningDumpTruck((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, Color.Black, checkBoxKit.Checked,
checkBoxTent.Checked, pictureBoxObject.Width,
pictureBoxObject.Height);
labelColor.BackColor = Color.White;
labelAddColor.BackColor = Color.Black;
break;
}
DrawCar();
}
public void AddEvent(Action<DrawningCar> ev)
{
if (EventAddCar == null)
{
EventAddCar = ev;
}
else
{
EventAddCar += ev;
}
}
private void buttonAdd_Click(object sender, EventArgs e)
{
if (_car == null)
{
return;
}
EventAddCar?.Invoke(_car);
Close();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,37 @@
using DumpTruck;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DumpTruck.MovementStrategy;
namespace DumpTruck.MovementStrategy
{
/// <summary>
/// Интерфейс для работы с перемещаемым объектом
/// </summary>
public interface IMoveableObject
{
/// <summary>
/// Получение координаты X объекта
/// </summary>
ObjectParameters? GetObjectPosition { get; }
/// <summary>
/// Шаг объекта
/// </summary>
int GetStep { get; }
/// <summary>
/// Проверка, можно ли переместиться по нужному направлению
/// </summary>
/// <param name="direction"></param>
/// <returns></returns>
bool CheckCanMove(DirectionType direction);
/// <summary>
/// Изменение направления пермещения объекта
/// </summary>
/// <param name="direction">Направление</param>
void MoveObject(DirectionType direction);
}
}

View File

@ -0,0 +1,50 @@
using DumpTruck.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DumpTruck.MovementStrategy
{
internal class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.RightBorder <= FieldWidth &&
objParams.RightBorder + GetStep() >= FieldWidth &&
objParams.DownBorder <= FieldHeight &&
objParams.DownBorder + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
var diffX = FieldWidth - objParams.ObjectMiddleHorizontal;
if (Math.Abs(diffX) > GetStep())
{
MoveRight();
}
var diffY = FieldHeight - objParams.ObjectMiddleVertical;
if (Math.Abs(diffY) > GetStep())
{
MoveDown();
}
}
}
}

View File

@ -0,0 +1,58 @@
using DumpTruck.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DumpTruck.MovementStrategy
{
internal class MoveToCenter : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return (objParams.ObjectMiddleHorizontal <= FieldWidth / 2 &&
objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 &&
objParams.ObjectMiddleVertical <= FieldHeight / 2 &&
objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2);
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
var diffX = objParams.ObjectMiddleHorizontal - FieldWidth / 2;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = objParams.ObjectMiddleVertical - FieldHeight / 2;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}
}

View File

@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DumpTruck.MovementStrategy
{
/// <summary>
/// Параметры-координаты объекта
/// </summary>
public class ObjectParameters
{
private readonly int _x;
private readonly int _y;
private readonly int _width;
private readonly int _height;
/// <summary>
/// Левая граница
/// </summary>
public int LeftBorder => _x;
/// <summary>
/// Верхняя граница
/// </summary>
public int TopBorder => _y;
/// <summary>
/// Правая граница
/// </summary>
public int RightBorder => _x + _width;
/// <summary>
/// Нижняя граница
/// </summary>
public int DownBorder => _y + _height;
/// <summary>
/// Середина объекта
/// </summary>
public int ObjectMiddleHorizontal => _x + _width / 2;
/// <summary>
/// Середина объекта
/// </summary>
public int ObjectMiddleVertical => _y + _height / 2;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
public ObjectParameters(int x, int y, int width, int height)
{
_x = x;
_y = y;
_width = width;
_height = height;
}
}
}

View File

@ -1,3 +1,12 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using Serilog;
using Serilog.Events;
using Serilog.Formatting.Json;
using Serilog.Configuration;
namespace DumpTruck
{
internal static class Program
@ -8,10 +17,23 @@ namespace DumpTruck
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
ApplicationConfiguration.Initialize(); string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: $"{pathNeed}debug.json", optional: false, reloadOnChange: true)
.Build();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormCarCollection());
}
}
}

View File

@ -0,0 +1,103 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DumpTruck.Properties {
using System;
/// <summary>
/// Класс ресурса со строгой типизацией для поиска локализованных строк и т.д.
/// </summary>
// Этот класс создан автоматически классом StronglyTypedResourceBuilder
// с помощью такого средства, как ResGen или Visual Studio.
// Чтобы добавить или удалить член, измените файл .ResX и снова запустите ResGen
// с параметром /str или перестройте свой проект VS.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Возвращает кэшированный экземпляр ResourceManager, использованный этим классом.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DumpTruck.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Перезаписывает свойство CurrentUICulture текущего потока для всех
/// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap down {
get {
object obj = ResourceManager.GetObject("down", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap left {
get {
object obj = ResourceManager.GetObject("left", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap right {
get {
object obj = ResourceManager.GetObject("right", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap up {
get {
object obj = ResourceManager.GetObject("up", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

View File

@ -0,0 +1,128 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms.VisualStyles;
using DumpTruck.Exceptions;
using System;
namespace DumpTruck.Generics
{
internal class SetGeneric<T>
where T : class
{
/// <summary>
/// Массив объектов, которые храним
/// </summary>
private readonly List<T?> _places;
/// <summary>
/// Количество объектов в массиве
/// </summary>
public int Count => _places.Count;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
///
public int startPointer = 0;
public int countMax = 0;
public SetGeneric(int count)
{
_places = new List<T?>(count);
countMax = count;
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="car">Добавляемый автомобиль</param>
/// <returns></returns>
public int Insert(T car)
{
if (_places.Count == countMax) { throw new StorageOverflowException(countMax); }
Insert(car, 0);
return 1;
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="car">Добавляемый автомобиль</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public int Insert(T car, int position)
{
if (_places.Count == countMax)
throw new StorageOverflowException(countMax);
if (!(position >= 0 && position <= Count)) return -1;
_places.Insert(position, car);
return position;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public bool Remove(int position)
{
if (!(position >= 0 && position < Count))
throw new TruckNotFoundException(position);
_places.RemoveAt(position);
return true;
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T? this[int position]
{
get
{
if (!(position >= 0 && position < Count))
return null;
return _places[position];
}
set
{
if (!(position >= 0 && position < Count && _places.Count < countMax))
return;
_places.Insert(position, value);
return;
}
}
/// <summary>
/// Проход по списку
/// </summary>
/// <returns></returns>
public IEnumerable<T?> GetCars(int? maxCars = null)
{
for (int i = 0; i < _places.Count; ++i)
{
yield return _places[i];
if (maxCars.HasValue && i == maxCars.Value)
{
yield break;
}
}
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T? Get(int position)
{
if (position < Count && position >= 0) { return _places[position]; }
return null;
}
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DumpTruck.MovementStrategy
{
public enum Status
{
NotInit,
InProgress,
Finish
}
}

View File

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

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

View File

@ -0,0 +1,15 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": { "path": "log.txt" }
}
],
"Properties": {
"Application": "Sample"
}
}
}