Compare commits
31 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
5af581e096 | ||
|
8c7a4a2c6b | ||
|
7e1761c5c8 | ||
|
8b75e1f20b | ||
|
feeb709fd2 | ||
|
3983ae497f | ||
|
d732ad2663 | ||
|
c223781a1c | ||
|
964619d691 | ||
|
7dbd8ad01f | ||
|
c7823ed7ee | ||
|
c05b306cb1 | ||
|
cd5b790f24 | ||
|
65f745bfeb | ||
|
b7d80bf20f | ||
|
47223fcbae | ||
|
0c14b3b223 | ||
|
542fe732ec | ||
|
d8f53d52d1 | ||
|
7a9cd6dcd2 | ||
|
f245f6a830 | ||
|
a2cf8e2bc7 | ||
|
2a48e6436c | ||
|
e1257a26e4 | ||
|
7bdefd69c1 | ||
|
fffb93e61b | ||
|
6745fe7894 | ||
|
344124546e | ||
|
33aeb63548 | ||
|
1a22fe73af | ||
|
d671e2b7f3 |
20
Liner/AppSettings.json
Normal file
20
Liner/AppSettings.json
Normal file
@ -0,0 +1,20 @@
|
||||
{
|
||||
"Serilog": {
|
||||
"Using": [ "Serilog.Sinks.File" ],
|
||||
"MinimumLevel": "Information",
|
||||
"WriteTo": [
|
||||
{
|
||||
"Name": "File",
|
||||
"Args": {
|
||||
"path": "Logs/log_.log",
|
||||
"rollingInterval": "Day",
|
||||
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
|
||||
}
|
||||
}
|
||||
],
|
||||
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
|
||||
"Properties": {
|
||||
"Application": "Loco"
|
||||
}
|
||||
}
|
||||
}
|
28
Liner/Direction.cs
Normal file
28
Liner/Direction.cs
Normal file
@ -0,0 +1,28 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Liner
|
||||
{
|
||||
public enum DirectionType
|
||||
{
|
||||
/// <summary>
|
||||
/// Вверх
|
||||
/// </summary>
|
||||
Up = 1,
|
||||
/// <summary>
|
||||
/// Вниз
|
||||
/// </summary>
|
||||
Down = 2,
|
||||
/// <summary>
|
||||
/// Влево
|
||||
/// </summary>
|
||||
Left = 3,
|
||||
/// <summary>
|
||||
/// Вправо
|
||||
/// </summary>
|
||||
Right = 4
|
||||
}
|
||||
}
|
87
Liner/Drawing/DrawingBigLiner.cs
Normal file
87
Liner/Drawing/DrawingBigLiner.cs
Normal file
@ -0,0 +1,87 @@
|
||||
using Liner.Entities;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Liner.Drawing
|
||||
{
|
||||
public class DrawingBigLiner : DrawingLiner
|
||||
{
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
/// <param name="speed">Скорость</param>
|
||||
/// <param name="weight">Вес лайнера</param>
|
||||
/// <param name="bodyColor">Основной цвет</param>
|
||||
/// <param name="swimmingPool">Признак наличия бассейна</param>
|
||||
/// <param name="deck">Признак наличия доп палубы</param>
|
||||
/// <param name="width">Ширина картинки</param>
|
||||
/// <param name="height">Высота картинки</param>
|
||||
public DrawingBigLiner(int speed, double weight, Color bottomColor, Color bodyColor, bool swimmingPool, bool deck, int width, int height)
|
||||
: base(speed,weight,bodyColor,width,height,100,80)
|
||||
{
|
||||
if(EntityLiner!= null)
|
||||
{
|
||||
EntityLiner = new EntityBigLiner(speed, weight,bottomColor, bodyColor, deck, swimmingPool);
|
||||
}
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// Прорисовка объекта
|
||||
/// </summary>
|
||||
/// <param name="g"></param>
|
||||
// высота палубы - 20 пикселей
|
||||
public override void DrawTransport(Graphics g)
|
||||
{
|
||||
if (EntityLiner is not EntityBigLiner liner)
|
||||
{
|
||||
return;
|
||||
}
|
||||
Pen pen = new(Color.Black);
|
||||
Brush poolBrush = new SolidBrush(Color.Blue);
|
||||
Brush bottomBrush = new SolidBrush(liner.BottomColor);
|
||||
Brush deckBrush = new SolidBrush(liner.BodyColor);
|
||||
// палуба
|
||||
Point[] firstDeck = {new Point(_startPosX + 30, _startPosY), new Point(_startPosX + 30 + 60, _startPosY),
|
||||
new Point(_startPosX + 30 + 60, _startPosY + 20), new Point(_startPosX + 30, _startPosY + 20)};
|
||||
int addY = 20;
|
||||
// нижний корпус
|
||||
Point[] bottom = {new Point(_startPosX, _startPosY), new Point(_startPosX + 100, _startPosY),
|
||||
new Point(_startPosX+80, _startPosY + 40), new Point(_startPosX + 20, _startPosY + 40)};
|
||||
// бассейн
|
||||
Point[] pool = {new Point(_startPosX + 10, _startPosY), new Point(_startPosX + 30, _startPosY),
|
||||
new Point(_startPosX+30, _startPosY + 10), new Point(_startPosX + 10, _startPosY + 10)};
|
||||
g.FillPolygon(deckBrush, firstDeck);
|
||||
g.DrawPolygon(pen, firstDeck);//рисуем палубу
|
||||
Point[] currentDeck = new Point[4]; //буффер для прорисовки доп палуб
|
||||
firstDeck.CopyTo(currentDeck, 0);
|
||||
if (liner.Deck) //рисуем вторую палубу
|
||||
{
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
currentDeck[i].Y += addY;
|
||||
}
|
||||
g.FillPolygon(deckBrush, currentDeck);
|
||||
g.DrawPolygon(pen, currentDeck);
|
||||
addY += 20;
|
||||
}
|
||||
for (int i = 0; i < 4; i++) //сдвигаем элементы вниз на кол-во палуб
|
||||
{
|
||||
bottom[i].Y += addY;
|
||||
pool[i].Y += addY;
|
||||
}
|
||||
g.FillPolygon(bottomBrush, bottom);
|
||||
g.DrawPolygon(pen, bottom);//рисуем нижний корпус
|
||||
if (liner.SwimmingPool) { g.FillPolygon(poolBrush, pool); }//рисуем бассейн
|
||||
}
|
||||
/// <summary>
|
||||
/// установка цвета большого лайнера
|
||||
/// </summary>
|
||||
public void SetAddColor(Color color)
|
||||
{
|
||||
(EntityLiner as EntityBigLiner).BodyColor = color;
|
||||
}
|
||||
}
|
||||
}
|
188
Liner/Drawing/DrawingLiner.cs
Normal file
188
Liner/Drawing/DrawingLiner.cs
Normal file
@ -0,0 +1,188 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Liner.Entities;
|
||||
using Liner.MovingStrategies;
|
||||
|
||||
namespace Liner.Drawing
|
||||
{
|
||||
public class DrawingLiner
|
||||
{
|
||||
/// <summary>
|
||||
/// Класс-сущность
|
||||
/// </summary>
|
||||
public EntityLiner? EntityLiner { get; protected set; }
|
||||
/// <summary>
|
||||
/// Ширина окна
|
||||
/// </summary>
|
||||
private int _pictureWidth;
|
||||
/// <summary>
|
||||
/// Высота окна
|
||||
/// </summary>
|
||||
private int _pictureHeight;
|
||||
/// <summary>
|
||||
/// Левая координата прорисовки лайнера
|
||||
/// </summary>
|
||||
protected int _startPosX;
|
||||
/// <summary>
|
||||
/// Верхняя координата прорисовки лайнера
|
||||
/// </summary>
|
||||
protected int _startPosY;
|
||||
/// <summary>
|
||||
/// Ширина прорисовки лайнера
|
||||
/// </summary>
|
||||
protected readonly int _linerWidth = 100;
|
||||
/// <summary>
|
||||
/// Высота прорисовки лайнера
|
||||
/// </summary>
|
||||
protected readonly int _linerHeight = 60;
|
||||
/// <summary>
|
||||
/// Координата X объекта
|
||||
/// </summary>
|
||||
public int GetPosX => _startPosX;
|
||||
/// <summary>
|
||||
/// Координата Y объекта
|
||||
/// </summary>
|
||||
public int GetPosY => _startPosY;
|
||||
/// <summary>
|
||||
/// Ширина объекта
|
||||
/// </summary>
|
||||
public int GetWidth => _linerWidth;
|
||||
/// <summary>
|
||||
/// Высота объекта
|
||||
/// </summary>
|
||||
public int GetHeight => _linerHeight;
|
||||
/// <summary>
|
||||
/// Получение объекта IMoveableObject из объекта DrawingLiner
|
||||
/// </summary>
|
||||
public IMoveableObject GetMoveableObject => new DrawingObjectLiner(this);
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
/// <param name="speed">Скорость</param>
|
||||
/// <param name="weight">Вес лайнера</param>
|
||||
/// <param name="bottomColor">Основной цвет</param>
|
||||
/// <param name="width">Ширина картинки</param>
|
||||
/// <param name="height">Высота картинки</param>
|
||||
public DrawingLiner(int speed, double weight, Color bottomColor, int width, int height)
|
||||
{
|
||||
_pictureWidth = width;
|
||||
_pictureHeight = height;
|
||||
EntityLiner = new EntityLiner(speed, weight, bottomColor);
|
||||
}
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
/// <param name="speed">Скорость</param>
|
||||
/// <param name="weight">Вес лайнера</param>
|
||||
/// <param name="bottomColor">Основной цвет</param>
|
||||
/// <param name="width">Ширина картинки</param>
|
||||
/// <param name="height">Высота картинки</param>
|
||||
/// <param name="linerWidth">Ширина прорисовки лайнера</param>
|
||||
/// <param name="linerHeight">Высота прорисовки лайнера</param>
|
||||
protected DrawingLiner(int speed, double weight, Color bottomColor, int width, int height,int linerWidth,int linerHeight)
|
||||
{
|
||||
_linerHeight = linerHeight;
|
||||
_linerWidth = linerWidth;
|
||||
_pictureWidth = width;
|
||||
_pictureHeight = height;
|
||||
EntityLiner = new EntityLiner(speed, weight, bottomColor);
|
||||
}
|
||||
/// <summary>
|
||||
/// Установка позиции
|
||||
/// </summary>
|
||||
/// <param name="x">Координата X</param>
|
||||
/// <param name="y">Координата Y</param>
|
||||
public void SetPosition(int x, int y)
|
||||
{
|
||||
if (x > _pictureWidth || y > _pictureHeight || x < 0 || y < 0)
|
||||
{
|
||||
_startPosX = 0;
|
||||
_startPosY = 0;
|
||||
}
|
||||
_startPosX = x;
|
||||
_startPosY = y;
|
||||
}
|
||||
// высота палубы - 20 пикселей
|
||||
public virtual void DrawTransport(Graphics g)
|
||||
{
|
||||
if (EntityLiner == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
Pen pen = new(Color.Black);
|
||||
Brush bottomBrush = new SolidBrush(EntityLiner.BottomColor);
|
||||
Brush deckBrush = new SolidBrush(Color.Black);//черная палуба по умолчанию
|
||||
// палуба
|
||||
Point[] firstDeck = {new Point(_startPosX + 30, _startPosY), new Point(_startPosX + 30 + 60, _startPosY),
|
||||
new Point(_startPosX + 30 + 60, _startPosY + 20), new Point(_startPosX + 30, _startPosY + 20)};
|
||||
// нижний корпус
|
||||
Point[] bottom = {new Point(_startPosX, _startPosY), new Point(_startPosX + 100, _startPosY),
|
||||
new Point(_startPosX+80, _startPosY + 40), new Point(_startPosX + 20, _startPosY + 40)};
|
||||
// бассейн
|
||||
g.FillPolygon(deckBrush, firstDeck);
|
||||
g.DrawPolygon(pen, firstDeck);//рисуем палубу
|
||||
for (int i = 0; i < 4; i++) //сдвигаем элементы вниз на кол-во палуб
|
||||
{
|
||||
bottom[i].Y += 20;
|
||||
}
|
||||
g.FillPolygon(bottomBrush, bottom);
|
||||
g.DrawPolygon(pen, bottom);//рисуем нижний корпус
|
||||
}
|
||||
/// <summary>
|
||||
/// Проверка, что объект может переместится по указанному направлению
|
||||
/// </summary>
|
||||
/// <param name="direction">Направление</param>
|
||||
/// <returns>true - можно переместится по указанному направлению</returns>
|
||||
public bool CanMove(DirectionType direction)
|
||||
{
|
||||
if (EntityLiner == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return direction switch
|
||||
{
|
||||
//влево
|
||||
DirectionType.Left => _startPosX - EntityLiner.Step > 0,
|
||||
//вверх
|
||||
DirectionType.Up => _startPosY - EntityLiner.Step > 0,
|
||||
//вправо
|
||||
DirectionType.Right => _startPosX + EntityLiner.Step + _linerWidth < _pictureWidth,
|
||||
//вниз
|
||||
DirectionType.Down => _startPosY + EntityLiner.Step + _linerHeight < _pictureHeight
|
||||
};
|
||||
}
|
||||
/// <summary>
|
||||
/// Изменение направления перемещения
|
||||
/// </summary>
|
||||
/// <param name="direction">Направление</param>
|
||||
public void MoveTransport(DirectionType direction)
|
||||
{
|
||||
if (!CanMove(direction) || EntityLiner == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
switch (direction)
|
||||
{
|
||||
//влево
|
||||
case DirectionType.Left:
|
||||
_startPosX -= (int)EntityLiner.Step;
|
||||
break;
|
||||
//вверх
|
||||
case DirectionType.Up:
|
||||
_startPosY -= (int)EntityLiner.Step;
|
||||
break;
|
||||
// вправо
|
||||
case DirectionType.Right:
|
||||
_startPosX += (int)EntityLiner.Step;
|
||||
break;
|
||||
//вниз
|
||||
case DirectionType.Down:
|
||||
_startPosY += (int)EntityLiner.Step;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
69
Liner/Drawing/ExtentionDrawingLiner.cs
Normal file
69
Liner/Drawing/ExtentionDrawingLiner.cs
Normal file
@ -0,0 +1,69 @@
|
||||
using Liner.Entities;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Liner.Drawing
|
||||
{
|
||||
/// <summary>
|
||||
/// Расширение для класса EntityLiner
|
||||
/// </summary>
|
||||
public static class ExtentionDrawningLiner
|
||||
{
|
||||
/// <summary>
|
||||
/// Создание объекта из строки
|
||||
/// </summary>
|
||||
/// <param name="info">Строка с данными для создания объекта</param>
|
||||
/// <param name="separatorForObject">Разделитель даннных</param>
|
||||
/// <param name="width">Ширина</param>
|
||||
/// <param name="height">Высота</param>
|
||||
/// <returns>Объект</returns>
|
||||
public static DrawingLiner? CreateDrawingLiner(this string info, char
|
||||
separatorForObject, int width, int height)
|
||||
{
|
||||
string[] strs = info.Split(separatorForObject);
|
||||
if (strs.Length == 3)
|
||||
{
|
||||
return new DrawingLiner(Convert.ToInt32(strs[0]),
|
||||
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
|
||||
}
|
||||
if (strs.Length == 6)
|
||||
{
|
||||
return new DrawingBigLiner(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;
|
||||
}
|
||||
/// <summary>
|
||||
/// Получение данных для сохранения в файл
|
||||
/// </summary>
|
||||
/// <param name="drawingLiner">Сохраняемый объект</param>
|
||||
/// <param name="separatorForObject">Разделитель даннных</param>
|
||||
/// <returns>Строка с данными по объекту</returns>
|
||||
public static string GetDataForSave(this DrawingLiner drawingLiner,
|
||||
char separatorForObject)
|
||||
{
|
||||
var liner = drawingLiner.EntityLiner;
|
||||
if (liner == null)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
var str =
|
||||
$"{liner.Speed}{separatorForObject}{liner.Weight}{separatorForObject}{liner.BottomColor.Name}";
|
||||
if (liner is not EntityBigLiner bigLiner)
|
||||
{
|
||||
return str;
|
||||
}
|
||||
return
|
||||
$"{str}{separatorForObject}{bigLiner.BodyColor.Name}{separatorForObject}{bigLiner.SwimmingPool}{separatorForObject}" +
|
||||
$"{bigLiner.Deck}";
|
||||
}
|
||||
}
|
||||
}
|
39
Liner/Entities/EntityBigLiner.cs
Normal file
39
Liner/Entities/EntityBigLiner.cs
Normal file
@ -0,0 +1,39 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Liner.Entities
|
||||
{
|
||||
public class EntityBigLiner : EntityLiner
|
||||
{
|
||||
/// <summary>
|
||||
/// Признак (опция) наличия бассейна
|
||||
/// </summary>
|
||||
public bool SwimmingPool { get; private set; }
|
||||
/// <summary>
|
||||
/// Признак (опция) наличия доп палубы
|
||||
/// </summary>
|
||||
public bool Deck { get; private set; }
|
||||
/// <summary>
|
||||
/// Доп цвет
|
||||
/// </summary>
|
||||
public Color BodyColor { get; set; }
|
||||
/// <summary>
|
||||
/// Конструктор с параметрами
|
||||
/// </summary>
|
||||
/// <param name="speed">Скорость</param>
|
||||
/// <param name="weight">Вес автомобиля</param>
|
||||
/// <param name="bodyColor">Основной цвет</param>
|
||||
/// <param name="bottomColor">Дополнительный цвет</param>
|
||||
/// <param name="deck">Признак наличия доп палубы</param>
|
||||
/// <param name="swimmingPool">Признак наличия бассейна</param>
|
||||
public EntityBigLiner(int speed, double weight, Color bottomColor,Color bodyColor,bool deck, bool swimmingPool) : base(speed, weight, bottomColor)
|
||||
{
|
||||
Deck = deck;
|
||||
SwimmingPool = swimmingPool;
|
||||
BodyColor = bodyColor;
|
||||
}
|
||||
}
|
||||
}
|
41
Liner/Entities/EntityLiner.cs
Normal file
41
Liner/Entities/EntityLiner.cs
Normal file
@ -0,0 +1,41 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.NetworkInformation;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Liner.Entities
|
||||
{
|
||||
public class EntityLiner
|
||||
{
|
||||
/// <summary>
|
||||
/// Скорость
|
||||
/// </summary>
|
||||
public int Speed { get; private set; }
|
||||
/// <summary>
|
||||
/// Вес
|
||||
/// </summary>
|
||||
public double Weight { get; private set; }
|
||||
/// <summary>
|
||||
/// Основной цвет
|
||||
/// </summary>
|
||||
public Color BottomColor { get; set; }
|
||||
/// <summary>
|
||||
/// Шаг
|
||||
/// </summary>
|
||||
public double Step => (double)Speed * 100 / Weight;
|
||||
/// <summary>
|
||||
/// Конструктор с параметрами
|
||||
/// </summary>
|
||||
/// <param name="speed">Скорость</param>
|
||||
/// <param name="weight">Вес лайнера</param>
|
||||
/// <param name="bottomColor">Основной цвет</param>
|
||||
public EntityLiner(int speed, double weight, Color bottomColor)
|
||||
{
|
||||
Speed = speed;
|
||||
Weight = weight;
|
||||
BottomColor = bottomColor;
|
||||
}
|
||||
}
|
||||
}
|
21
Liner/Exceptions/LinerNotFoundException.cs
Normal file
21
Liner/Exceptions/LinerNotFoundException.cs
Normal 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;
|
||||
|
||||
namespace Liner.Exceptions
|
||||
{
|
||||
[Serializable]
|
||||
internal class LinerNotFoundException : ApplicationException
|
||||
{
|
||||
public LinerNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
|
||||
public LinerNotFoundException() : base() { }
|
||||
public LinerNotFoundException(string message) : base(message) { }
|
||||
public LinerNotFoundException(string message, Exception exception) :
|
||||
base(message, exception) { }
|
||||
protected LinerNotFoundException(SerializationInfo info,
|
||||
StreamingContext contex) : base(info, contex) { }
|
||||
}
|
||||
}
|
21
Liner/Exceptions/StorageOverflowException.cs
Normal file
21
Liner/Exceptions/StorageOverflowException.cs
Normal 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;
|
||||
|
||||
namespace Liner.Exceptions
|
||||
{
|
||||
[Serializable]
|
||||
internal class StorageOverflowException : ApplicationException
|
||||
{
|
||||
public StorageOverflowException(int count) : base($"В наборе превышено допустимое количество: {count}") { }
|
||||
public StorageOverflowException() : base() { }
|
||||
public StorageOverflowException(string message) : base(message) { }
|
||||
public StorageOverflowException(string message, Exception exception)
|
||||
: base(message, exception) { }
|
||||
protected StorageOverflowException(SerializationInfo info,
|
||||
StreamingContext contex) : base(info, contex) { }
|
||||
}
|
||||
}
|
46
Liner/Form1.Designer.cs
generated
46
Liner/Form1.Designer.cs
generated
@ -1,46 +0,0 @@
|
||||
namespace Liner
|
||||
{
|
||||
partial class Form1
|
||||
{
|
||||
/// <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()
|
||||
{
|
||||
SuspendLayout();
|
||||
//
|
||||
// Form1
|
||||
//
|
||||
AutoScaleDimensions = new SizeF(7F, 15F);
|
||||
AutoScaleMode = AutoScaleMode.Font;
|
||||
ClientSize = new Size(800, 450);
|
||||
Name = "Form1";
|
||||
Text = "Form1";
|
||||
Load += Form1_Load;
|
||||
ResumeLayout(false);
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
@ -1,10 +0,0 @@
|
||||
namespace Liner
|
||||
{
|
||||
public partial class Form1 : Form
|
||||
{
|
||||
public Form1()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
}
|
288
Liner/FormLinerCollection.Designer.cs
generated
Normal file
288
Liner/FormLinerCollection.Designer.cs
generated
Normal file
@ -0,0 +1,288 @@
|
||||
namespace Liner
|
||||
{
|
||||
partial class FormLinerCollection
|
||||
{
|
||||
/// <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()
|
||||
{
|
||||
groupBoxTools = new GroupBox();
|
||||
buttonSortByType = new Button();
|
||||
buttonSortByColor = new Button();
|
||||
Storages = new GroupBox();
|
||||
listBoxStorages = new ListBox();
|
||||
buttonDeleteSet = new Button();
|
||||
textBoxStorageName = new TextBox();
|
||||
buttonAddStorage = new Button();
|
||||
buttonRefreshCollection = new Button();
|
||||
buttonDeleteLiner = new Button();
|
||||
textBoxNumber = new TextBox();
|
||||
buttonAddLiner = new Button();
|
||||
pictureBoxCollection = new PictureBox();
|
||||
FileMenuStrip = new MenuStrip();
|
||||
FileToolStripMenuItem = new ToolStripMenuItem();
|
||||
SaveToolStripMenuItem = new ToolStripMenuItem();
|
||||
LoadToolStripMenuItem = new ToolStripMenuItem();
|
||||
openFileDialog = new OpenFileDialog();
|
||||
saveFileDialog = new SaveFileDialog();
|
||||
groupBoxTools.SuspendLayout();
|
||||
Storages.SuspendLayout();
|
||||
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
|
||||
FileMenuStrip.SuspendLayout();
|
||||
SuspendLayout();
|
||||
//
|
||||
// groupBoxTools
|
||||
//
|
||||
groupBoxTools.Controls.Add(buttonSortByType);
|
||||
groupBoxTools.Controls.Add(buttonSortByColor);
|
||||
groupBoxTools.Controls.Add(Storages);
|
||||
groupBoxTools.Controls.Add(buttonRefreshCollection);
|
||||
groupBoxTools.Controls.Add(buttonDeleteLiner);
|
||||
groupBoxTools.Controls.Add(textBoxNumber);
|
||||
groupBoxTools.Controls.Add(buttonAddLiner);
|
||||
groupBoxTools.Location = new Point(845, 0);
|
||||
groupBoxTools.Margin = new Padding(3, 4, 3, 4);
|
||||
groupBoxTools.Name = "groupBoxTools";
|
||||
groupBoxTools.Padding = new Padding(3, 4, 3, 4);
|
||||
groupBoxTools.Size = new Size(241, 753);
|
||||
groupBoxTools.TabIndex = 0;
|
||||
groupBoxTools.TabStop = false;
|
||||
groupBoxTools.Text = "Tools";
|
||||
//
|
||||
// buttonSortByType
|
||||
//
|
||||
buttonSortByType.Location = new Point(28, 413);
|
||||
buttonSortByType.Margin = new Padding(3, 4, 3, 4);
|
||||
buttonSortByType.Name = "buttonSortByType";
|
||||
buttonSortByType.Size = new Size(190, 41);
|
||||
buttonSortByType.TabIndex = 8;
|
||||
buttonSortByType.Text = "Sort By Type";
|
||||
buttonSortByType.UseVisualStyleBackColor = true;
|
||||
buttonSortByType.Click += ButtonSortByType_Click;
|
||||
//
|
||||
// buttonSortByColor
|
||||
//
|
||||
buttonSortByColor.Location = new Point(28, 462);
|
||||
buttonSortByColor.Margin = new Padding(3, 4, 3, 4);
|
||||
buttonSortByColor.Name = "buttonSortByColor";
|
||||
buttonSortByColor.Size = new Size(190, 41);
|
||||
buttonSortByColor.TabIndex = 7;
|
||||
buttonSortByColor.Text = "Sort By Color";
|
||||
buttonSortByColor.UseVisualStyleBackColor = true;
|
||||
buttonSortByColor.Click += ButtonSortByColor_Click;
|
||||
//
|
||||
// Storages
|
||||
//
|
||||
Storages.Controls.Add(listBoxStorages);
|
||||
Storages.Controls.Add(buttonDeleteSet);
|
||||
Storages.Controls.Add(textBoxStorageName);
|
||||
Storages.Controls.Add(buttonAddStorage);
|
||||
Storages.Location = new Point(8, 29);
|
||||
Storages.Margin = new Padding(3, 4, 3, 4);
|
||||
Storages.Name = "Storages";
|
||||
Storages.Padding = new Padding(3, 4, 3, 4);
|
||||
Storages.Size = new Size(229, 364);
|
||||
Storages.TabIndex = 4;
|
||||
Storages.TabStop = false;
|
||||
Storages.Text = "Sets";
|
||||
//
|
||||
// listBoxStorages
|
||||
//
|
||||
listBoxStorages.FormattingEnabled = true;
|
||||
listBoxStorages.ItemHeight = 20;
|
||||
listBoxStorages.Location = new Point(7, 151);
|
||||
listBoxStorages.Margin = new Padding(3, 4, 3, 4);
|
||||
listBoxStorages.Name = "listBoxStorages";
|
||||
listBoxStorages.Size = new Size(213, 144);
|
||||
listBoxStorages.TabIndex = 4;
|
||||
listBoxStorages.SelectedIndexChanged += ListBoxObjects_SelectedIndexChanged;
|
||||
//
|
||||
// buttonDeleteSet
|
||||
//
|
||||
buttonDeleteSet.Location = new Point(11, 304);
|
||||
buttonDeleteSet.Margin = new Padding(3, 4, 3, 4);
|
||||
buttonDeleteSet.Name = "buttonDeleteSet";
|
||||
buttonDeleteSet.Size = new Size(210, 40);
|
||||
buttonDeleteSet.TabIndex = 3;
|
||||
buttonDeleteSet.Text = "Delete Set";
|
||||
buttonDeleteSet.UseVisualStyleBackColor = true;
|
||||
buttonDeleteSet.Click += ButtonRemoveObject_Click;
|
||||
//
|
||||
// textBoxStorageName
|
||||
//
|
||||
textBoxStorageName.Location = new Point(39, 52);
|
||||
textBoxStorageName.Margin = new Padding(3, 4, 3, 4);
|
||||
textBoxStorageName.Name = "textBoxStorageName";
|
||||
textBoxStorageName.Size = new Size(158, 27);
|
||||
textBoxStorageName.TabIndex = 2;
|
||||
//
|
||||
// buttonAddStorage
|
||||
//
|
||||
buttonAddStorage.Location = new Point(11, 91);
|
||||
buttonAddStorage.Margin = new Padding(3, 4, 3, 4);
|
||||
buttonAddStorage.Name = "buttonAddStorage";
|
||||
buttonAddStorage.Size = new Size(210, 40);
|
||||
buttonAddStorage.TabIndex = 1;
|
||||
buttonAddStorage.Text = "Add Set";
|
||||
buttonAddStorage.UseVisualStyleBackColor = true;
|
||||
buttonAddStorage.Click += ButtonAddObject_Click;
|
||||
//
|
||||
// buttonRefreshCollection
|
||||
//
|
||||
buttonRefreshCollection.Location = new Point(13, 691);
|
||||
buttonRefreshCollection.Margin = new Padding(3, 4, 3, 4);
|
||||
buttonRefreshCollection.Name = "buttonRefreshCollection";
|
||||
buttonRefreshCollection.Size = new Size(222, 53);
|
||||
buttonRefreshCollection.TabIndex = 3;
|
||||
buttonRefreshCollection.Text = "Refresh Collection";
|
||||
buttonRefreshCollection.UseVisualStyleBackColor = true;
|
||||
buttonRefreshCollection.Click += ButtonRefreshCollection_Click;
|
||||
//
|
||||
// buttonDeleteLiner
|
||||
//
|
||||
buttonDeleteLiner.Location = new Point(13, 607);
|
||||
buttonDeleteLiner.Margin = new Padding(3, 4, 3, 4);
|
||||
buttonDeleteLiner.Name = "buttonDeleteLiner";
|
||||
buttonDeleteLiner.Size = new Size(222, 53);
|
||||
buttonDeleteLiner.TabIndex = 2;
|
||||
buttonDeleteLiner.Text = "Delete Liner";
|
||||
buttonDeleteLiner.UseVisualStyleBackColor = true;
|
||||
buttonDeleteLiner.Click += ButtonRemoveLiner_Click;
|
||||
//
|
||||
// textBoxNumber
|
||||
//
|
||||
textBoxNumber.Location = new Point(47, 572);
|
||||
textBoxNumber.Margin = new Padding(3, 4, 3, 4);
|
||||
textBoxNumber.Name = "textBoxNumber";
|
||||
textBoxNumber.Size = new Size(158, 27);
|
||||
textBoxNumber.TabIndex = 1;
|
||||
//
|
||||
// buttonAddLiner
|
||||
//
|
||||
buttonAddLiner.Location = new Point(13, 511);
|
||||
buttonAddLiner.Margin = new Padding(3, 4, 3, 4);
|
||||
buttonAddLiner.Name = "buttonAddLiner";
|
||||
buttonAddLiner.Size = new Size(222, 53);
|
||||
buttonAddLiner.TabIndex = 0;
|
||||
buttonAddLiner.Text = "Add Liner";
|
||||
buttonAddLiner.UseVisualStyleBackColor = true;
|
||||
buttonAddLiner.Click += ButtonAddLiner_Click;
|
||||
//
|
||||
// pictureBoxCollection
|
||||
//
|
||||
pictureBoxCollection.Location = new Point(2, 36);
|
||||
pictureBoxCollection.Margin = new Padding(3, 4, 3, 4);
|
||||
pictureBoxCollection.Name = "pictureBoxCollection";
|
||||
pictureBoxCollection.Size = new Size(835, 717);
|
||||
pictureBoxCollection.TabIndex = 1;
|
||||
pictureBoxCollection.TabStop = false;
|
||||
//
|
||||
// FileMenuStrip
|
||||
//
|
||||
FileMenuStrip.ImageScalingSize = new Size(20, 20);
|
||||
FileMenuStrip.Items.AddRange(new ToolStripItem[] { FileToolStripMenuItem });
|
||||
FileMenuStrip.Location = new Point(0, 0);
|
||||
FileMenuStrip.Name = "FileMenuStrip";
|
||||
FileMenuStrip.Padding = new Padding(7, 3, 0, 3);
|
||||
FileMenuStrip.Size = new Size(1087, 30);
|
||||
FileMenuStrip.TabIndex = 2;
|
||||
FileMenuStrip.Text = "FileMenuStrip";
|
||||
//
|
||||
// FileToolStripMenuItem
|
||||
//
|
||||
FileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { SaveToolStripMenuItem, LoadToolStripMenuItem });
|
||||
FileToolStripMenuItem.Name = "FileToolStripMenuItem";
|
||||
FileToolStripMenuItem.Size = new Size(49, 24);
|
||||
FileToolStripMenuItem.Text = "FILE";
|
||||
//
|
||||
// SaveToolStripMenuItem
|
||||
//
|
||||
SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
|
||||
SaveToolStripMenuItem.Size = new Size(130, 26);
|
||||
SaveToolStripMenuItem.Text = "SAVE";
|
||||
SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
|
||||
//
|
||||
// LoadToolStripMenuItem
|
||||
//
|
||||
LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
|
||||
LoadToolStripMenuItem.Size = new Size(130, 26);
|
||||
LoadToolStripMenuItem.Text = "LOAD";
|
||||
LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
|
||||
//
|
||||
// openFileDialog
|
||||
//
|
||||
openFileDialog.Filter = "txt file | *.txt";
|
||||
//
|
||||
// saveFileDialog
|
||||
//
|
||||
saveFileDialog.FileName = "saveFile";
|
||||
saveFileDialog.Filter = "txt file | *.txt";
|
||||
//
|
||||
// FormLinerCollection
|
||||
//
|
||||
AutoScaleDimensions = new SizeF(8F, 20F);
|
||||
AutoScaleMode = AutoScaleMode.Font;
|
||||
ClientSize = new Size(1087, 757);
|
||||
Controls.Add(FileMenuStrip);
|
||||
Controls.Add(pictureBoxCollection);
|
||||
Controls.Add(groupBoxTools);
|
||||
MainMenuStrip = FileMenuStrip;
|
||||
Margin = new Padding(3, 4, 3, 4);
|
||||
Name = "FormLinerCollection";
|
||||
Text = "Liner Collection";
|
||||
groupBoxTools.ResumeLayout(false);
|
||||
groupBoxTools.PerformLayout();
|
||||
Storages.ResumeLayout(false);
|
||||
Storages.PerformLayout();
|
||||
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
|
||||
FileMenuStrip.ResumeLayout(false);
|
||||
FileMenuStrip.PerformLayout();
|
||||
ResumeLayout(false);
|
||||
PerformLayout();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
private GroupBox groupBoxTools;
|
||||
private TextBox textBoxNumber;
|
||||
private Button buttonAddLiner;
|
||||
private Button buttonRefreshCollection;
|
||||
private Button buttonDeleteLiner;
|
||||
private PictureBox pictureBoxCollection;
|
||||
private GroupBox Storages;
|
||||
private ListBox listBoxStorages;
|
||||
private Button buttonDeleteSet;
|
||||
private TextBox textBoxStorageName;
|
||||
private Button buttonAddStorage;
|
||||
private MenuStrip FileMenuStrip;
|
||||
private ToolStripMenuItem FileToolStripMenuItem;
|
||||
private ToolStripMenuItem SaveToolStripMenuItem;
|
||||
private ToolStripMenuItem LoadToolStripMenuItem;
|
||||
private OpenFileDialog openFileDialog;
|
||||
private SaveFileDialog saveFileDialog;
|
||||
private Button buttonSortByType;
|
||||
private Button buttonSortByColor;
|
||||
}
|
||||
}
|
311
Liner/FormLinerCollection.cs
Normal file
311
Liner/FormLinerCollection.cs
Normal file
@ -0,0 +1,311 @@
|
||||
using Liner.Drawing;
|
||||
using Liner.Generics;
|
||||
using Liner.MovingStrategies;
|
||||
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 Microsoft.Extensions.Logging;
|
||||
using Liner.Exceptions;
|
||||
using System.Xml.Linq;
|
||||
namespace Liner
|
||||
{
|
||||
/// <summary>
|
||||
/// Форма для работы с набором объектов класса DrawingLiner
|
||||
/// </summary>
|
||||
public partial class FormLinerCollection : Form
|
||||
{
|
||||
/// <summary>
|
||||
/// Набор объектов
|
||||
/// </summary>
|
||||
private readonly LinersGenericStorage _storage;
|
||||
/// <summary>
|
||||
/// Логер
|
||||
/// </summary>
|
||||
private readonly ILogger _logger;
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public FormLinerCollection(ILogger<FormLinerCollection> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_storage = new LinersGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
|
||||
_logger = logger;
|
||||
}
|
||||
/// <summary>
|
||||
/// Добавление объекта в набор
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonAddLiner_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (listBoxStorages.SelectedIndex == -1)
|
||||
{
|
||||
_logger.LogWarning($"Добавление лайнера не удалось (индекс вне границ)");
|
||||
return;
|
||||
}
|
||||
var formLinerConfig = new FormLinerConfig();
|
||||
formLinerConfig.AddEvent(AddLiner);
|
||||
formLinerConfig.Show();
|
||||
}
|
||||
|
||||
private void AddLiner(DrawingLiner liner)
|
||||
{
|
||||
if (listBoxStorages.SelectedIndex == -1)
|
||||
{
|
||||
_logger.LogWarning($"Добавление лайнера не удалось (индекс вне границ)");
|
||||
return;
|
||||
}
|
||||
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
|
||||
if (obj == null)
|
||||
{
|
||||
_logger.LogWarning($"Добавление лайнера не удалось (нет хранилища)");
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
if ((obj + liner) != -1)
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
_logger.LogInformation($"Добавление лайнера успешно {listBoxStorages.SelectedItem.ToString()}");
|
||||
pictureBoxCollection.Image = obj.ShowLiners();
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
}
|
||||
}
|
||||
catch (ApplicationException ex)
|
||||
{
|
||||
_logger.LogWarning($"Добавление лайнера в {listBoxStorages.SelectedItem.ToString()} не удалось (переполнение коллекции)");
|
||||
MessageBox.Show(ex.Message);
|
||||
}
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message);
|
||||
_logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Удаление объекта из набора
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonRemoveLiner_Click(object sender, EventArgs e)
|
||||
{
|
||||
int pos = 0; //фикс недосмотра
|
||||
if (listBoxStorages.SelectedIndex == -1)
|
||||
{
|
||||
_logger.LogWarning($"Удаление лайнера не удалось (индекс вне границ)");
|
||||
return;
|
||||
}
|
||||
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
|
||||
if (obj == null)
|
||||
{
|
||||
_logger.LogWarning($"Удаление лайнера не удалось (нет хранилища)");
|
||||
return;
|
||||
}
|
||||
if (MessageBox.Show("Удалить объект?", "Удаление",
|
||||
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
|
||||
{
|
||||
_logger.LogWarning($"Удаление лайнера не удалось (выбран вариант 'Нет')");
|
||||
return;
|
||||
}
|
||||
if (textBoxNumber.Text != "") //улучшил проверку
|
||||
{
|
||||
if(!int.TryParse(textBoxNumber.Text, out pos))
|
||||
{
|
||||
_logger.LogWarning($"Удаление лайнера не удалось (неверный формат)");
|
||||
return;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogWarning($"Удаление лайнера не удалось (пустое поле ввода)");
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
if (obj - pos)
|
||||
{
|
||||
_logger.LogInformation($"Удаление лайнера успешно {listBoxStorages.SelectedItem.ToString()} {pos}");
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBoxCollection.Image = obj.ShowLiners();
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogWarning($"Удаление лайнера не удалось(обьект не найден)");
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
}
|
||||
}
|
||||
catch (LinerNotFoundException ex)
|
||||
{
|
||||
_logger.LogWarning($"Удаление лайнера не удалось {ex.Message}");
|
||||
MessageBox.Show(ex.Message);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Добавление набора в коллекцию
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonAddObject_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (string.IsNullOrEmpty(textBoxStorageName.Text))
|
||||
{
|
||||
_logger.LogWarning($"Обновление набора не удалось (не все данные заполнены)");
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
return;
|
||||
}
|
||||
_storage.AddSet(textBoxStorageName.Text);
|
||||
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text} ");
|
||||
ReloadObjects();
|
||||
}
|
||||
/// <summary>
|
||||
/// Выбор набора
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e)
|
||||
{
|
||||
pictureBoxCollection.Image =
|
||||
_storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowLiners();
|
||||
}
|
||||
/// <summary>
|
||||
/// Удаление набора
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonRemoveObject_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (listBoxStorages.SelectedIndex == -1)
|
||||
{
|
||||
_logger.LogWarning($"Удаление набора не удалось (индекс вне границ)");
|
||||
return;
|
||||
}
|
||||
if (MessageBox.Show($"Удалить объект {listBoxStorages.SelectedItem}?", "Удаление",
|
||||
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
|
||||
{
|
||||
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
|
||||
_storage.DelSet(name);
|
||||
_logger.LogInformation($"Удаление набора успешно: {name}");
|
||||
ReloadObjects();
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Обновление рисунка по набору
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (listBoxStorages.SelectedIndex == -1)
|
||||
{
|
||||
_logger.LogWarning($"Обновление объектов не удалось (индекс вне границ)");
|
||||
return;
|
||||
}
|
||||
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
|
||||
if (obj == null)
|
||||
{
|
||||
_logger.LogWarning($"Обновление объектов не удалось (нет хранилища)");
|
||||
return;
|
||||
}
|
||||
_logger.LogInformation($"Обновление объектов успешно");
|
||||
pictureBoxCollection.Image = obj.ShowLiners();
|
||||
}
|
||||
/// <summary>
|
||||
/// Заполнение listBoxObjects
|
||||
/// </summary>
|
||||
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].Name);
|
||||
}
|
||||
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 SaveToolStripMenuItem_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
try
|
||||
{
|
||||
_storage.SaveData(saveFileDialog.FileName);
|
||||
_logger.LogInformation($"Cохранение успешно");
|
||||
MessageBox.Show("Сохранение прошло успешно",
|
||||
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
}
|
||||
catch(Exception ex)
|
||||
{
|
||||
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogWarning($"Сохранение не удалось {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
try
|
||||
{
|
||||
_storage.LoadData(openFileDialog.FileName);
|
||||
_logger.LogInformation($"Загрузка успешна");
|
||||
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
ReloadObjects();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogWarning($"Загрузка не удалась {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Сортировка по сравнителю
|
||||
/// </summary>
|
||||
/// <param name="comparer"></param>
|
||||
private void CompareLiners(IComparer<DrawingLiner?> comparer)
|
||||
{
|
||||
if (listBoxStorages.SelectedIndex == -1)
|
||||
{
|
||||
return;
|
||||
}
|
||||
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
|
||||
if (obj == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
obj.Sort(comparer);
|
||||
pictureBoxCollection.Image = obj.ShowLiners();
|
||||
}
|
||||
/// <summary>
|
||||
/// Сортировка по типу
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonSortByType_Click(object sender, EventArgs e) => CompareLiners(new LinerCompareByType());
|
||||
/// <summary>
|
||||
/// Сортировка по цвету
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonSortByColor_Click(object sender, EventArgs e) => CompareLiners(new LinerCompareByColor());
|
||||
}
|
||||
}
|
129
Liner/FormLinerCollection.resx
Normal file
129
Liner/FormLinerCollection.resx
Normal file
@ -0,0 +1,129 @@
|
||||
<?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>
|
||||
<metadata name="FileMenuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>17, 17</value>
|
||||
</metadata>
|
||||
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>144, 17</value>
|
||||
</metadata>
|
||||
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>284, 17</value>
|
||||
</metadata>
|
||||
</root>
|
356
Liner/FormLinerConfig.Designer.cs
generated
Normal file
356
Liner/FormLinerConfig.Designer.cs
generated
Normal file
@ -0,0 +1,356 @@
|
||||
namespace Liner
|
||||
{
|
||||
partial class FormLinerConfig
|
||||
{
|
||||
/// <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()
|
||||
{
|
||||
groupBoxParametrs = new GroupBox();
|
||||
labelModifiedObject = new Label();
|
||||
labelSimpleObject = new Label();
|
||||
groupBoxColors = new GroupBox();
|
||||
panelPurple = new Panel();
|
||||
panelBlack = new Panel();
|
||||
panelGray = new Panel();
|
||||
panelWhite = new Panel();
|
||||
panelYellow = new Panel();
|
||||
panelBlue = new Panel();
|
||||
panelGreen = new Panel();
|
||||
panelRed = new Panel();
|
||||
checkBoxDeck = new CheckBox();
|
||||
checkBoxPool = new CheckBox();
|
||||
numericUpDownWeight = new NumericUpDown();
|
||||
numericUpDownSpeed = new NumericUpDown();
|
||||
TextWeight = new Label();
|
||||
TextSpeed = new Label();
|
||||
panelObject = new Panel();
|
||||
pictureBoxObject = new PictureBox();
|
||||
labelAddColor = new Label();
|
||||
labelMainColor = new Label();
|
||||
buttonOk = new Button();
|
||||
buttonCancel = new Button();
|
||||
groupBoxParametrs.SuspendLayout();
|
||||
groupBoxColors.SuspendLayout();
|
||||
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
|
||||
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
|
||||
panelObject.SuspendLayout();
|
||||
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
|
||||
SuspendLayout();
|
||||
//
|
||||
// groupBoxParametrs
|
||||
//
|
||||
groupBoxParametrs.Controls.Add(labelModifiedObject);
|
||||
groupBoxParametrs.Controls.Add(labelSimpleObject);
|
||||
groupBoxParametrs.Controls.Add(groupBoxColors);
|
||||
groupBoxParametrs.Controls.Add(checkBoxDeck);
|
||||
groupBoxParametrs.Controls.Add(checkBoxPool);
|
||||
groupBoxParametrs.Controls.Add(numericUpDownWeight);
|
||||
groupBoxParametrs.Controls.Add(numericUpDownSpeed);
|
||||
groupBoxParametrs.Controls.Add(TextWeight);
|
||||
groupBoxParametrs.Controls.Add(TextSpeed);
|
||||
groupBoxParametrs.Location = new Point(12, 12);
|
||||
groupBoxParametrs.Name = "groupBoxParametrs";
|
||||
groupBoxParametrs.Size = new Size(588, 307);
|
||||
groupBoxParametrs.TabIndex = 0;
|
||||
groupBoxParametrs.TabStop = false;
|
||||
groupBoxParametrs.Text = "Parametrs";
|
||||
//
|
||||
// labelModifiedObject
|
||||
//
|
||||
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
|
||||
labelModifiedObject.Location = new Point(419, 241);
|
||||
labelModifiedObject.Name = "labelModifiedObject";
|
||||
labelModifiedObject.Size = new Size(120, 50);
|
||||
labelModifiedObject.TabIndex = 8;
|
||||
labelModifiedObject.Text = "Big";
|
||||
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
|
||||
labelModifiedObject.MouseDown += LabelObject_MouseDown;
|
||||
//
|
||||
// labelSimpleObject
|
||||
//
|
||||
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
|
||||
labelSimpleObject.Location = new Point(278, 241);
|
||||
labelSimpleObject.Name = "labelSimpleObject";
|
||||
labelSimpleObject.Size = new Size(120, 50);
|
||||
labelSimpleObject.TabIndex = 7;
|
||||
labelSimpleObject.Text = "Small";
|
||||
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
|
||||
labelSimpleObject.MouseDown += LabelObject_MouseDown;
|
||||
//
|
||||
// groupBoxColors
|
||||
//
|
||||
groupBoxColors.Controls.Add(panelPurple);
|
||||
groupBoxColors.Controls.Add(panelBlack);
|
||||
groupBoxColors.Controls.Add(panelGray);
|
||||
groupBoxColors.Controls.Add(panelWhite);
|
||||
groupBoxColors.Controls.Add(panelYellow);
|
||||
groupBoxColors.Controls.Add(panelBlue);
|
||||
groupBoxColors.Controls.Add(panelGreen);
|
||||
groupBoxColors.Controls.Add(panelRed);
|
||||
groupBoxColors.Location = new Point(244, 22);
|
||||
groupBoxColors.Name = "groupBoxColors";
|
||||
groupBoxColors.Size = new Size(338, 200);
|
||||
groupBoxColors.TabIndex = 6;
|
||||
groupBoxColors.TabStop = false;
|
||||
groupBoxColors.Text = "Colors";
|
||||
//
|
||||
// panelPurple
|
||||
//
|
||||
panelPurple.BackColor = Color.Purple;
|
||||
panelPurple.Location = new Point(248, 110);
|
||||
panelPurple.Name = "panelPurple";
|
||||
panelPurple.Size = new Size(57, 49);
|
||||
panelPurple.TabIndex = 1;
|
||||
//
|
||||
// panelBlack
|
||||
//
|
||||
panelBlack.BackColor = Color.Black;
|
||||
panelBlack.Location = new Point(175, 110);
|
||||
panelBlack.Name = "panelBlack";
|
||||
panelBlack.Size = new Size(57, 49);
|
||||
panelBlack.TabIndex = 1;
|
||||
//
|
||||
// panelGray
|
||||
//
|
||||
panelGray.BackColor = Color.Gray;
|
||||
panelGray.Location = new Point(97, 110);
|
||||
panelGray.Name = "panelGray";
|
||||
panelGray.Size = new Size(57, 49);
|
||||
panelGray.TabIndex = 5;
|
||||
//
|
||||
// panelWhite
|
||||
//
|
||||
panelWhite.BackColor = Color.White;
|
||||
panelWhite.Location = new Point(18, 110);
|
||||
panelWhite.Name = "panelWhite";
|
||||
panelWhite.Size = new Size(57, 49);
|
||||
panelWhite.TabIndex = 4;
|
||||
//
|
||||
// panelYellow
|
||||
//
|
||||
panelYellow.BackColor = Color.Yellow;
|
||||
panelYellow.Location = new Point(248, 22);
|
||||
panelYellow.Name = "panelYellow";
|
||||
panelYellow.Size = new Size(57, 49);
|
||||
panelYellow.TabIndex = 3;
|
||||
//
|
||||
// panelBlue
|
||||
//
|
||||
panelBlue.BackColor = Color.Blue;
|
||||
panelBlue.Location = new Point(175, 22);
|
||||
panelBlue.Name = "panelBlue";
|
||||
panelBlue.Size = new Size(57, 49);
|
||||
panelBlue.TabIndex = 2;
|
||||
//
|
||||
// panelGreen
|
||||
//
|
||||
panelGreen.BackColor = Color.Green;
|
||||
panelGreen.Location = new Point(97, 22);
|
||||
panelGreen.Name = "panelGreen";
|
||||
panelGreen.Size = new Size(57, 49);
|
||||
panelGreen.TabIndex = 1;
|
||||
//
|
||||
// panelRed
|
||||
//
|
||||
panelRed.BackColor = Color.Red;
|
||||
panelRed.Location = new Point(18, 22);
|
||||
panelRed.Name = "panelRed";
|
||||
panelRed.Size = new Size(57, 49);
|
||||
panelRed.TabIndex = 0;
|
||||
//
|
||||
// checkBoxDeck
|
||||
//
|
||||
checkBoxDeck.AutoSize = true;
|
||||
checkBoxDeck.Location = new Point(17, 162);
|
||||
checkBoxDeck.Name = "checkBoxDeck";
|
||||
checkBoxDeck.Size = new Size(110, 19);
|
||||
checkBoxDeck.TabIndex = 5;
|
||||
checkBoxDeck.Text = "Additional Deck";
|
||||
checkBoxDeck.UseVisualStyleBackColor = true;
|
||||
//
|
||||
// checkBoxPool
|
||||
//
|
||||
checkBoxPool.AutoSize = true;
|
||||
checkBoxPool.Location = new Point(17, 137);
|
||||
checkBoxPool.Name = "checkBoxPool";
|
||||
checkBoxPool.Size = new Size(110, 19);
|
||||
checkBoxPool.TabIndex = 4;
|
||||
checkBoxPool.Text = "Swimming pool";
|
||||
checkBoxPool.UseVisualStyleBackColor = true;
|
||||
//
|
||||
// numericUpDownWeight
|
||||
//
|
||||
numericUpDownWeight.Location = new Point(81, 70);
|
||||
numericUpDownWeight.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
|
||||
numericUpDownWeight.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
|
||||
numericUpDownWeight.Name = "numericUpDownWeight";
|
||||
numericUpDownWeight.Size = new Size(70, 23);
|
||||
numericUpDownWeight.TabIndex = 3;
|
||||
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
|
||||
//
|
||||
// numericUpDownSpeed
|
||||
//
|
||||
numericUpDownSpeed.Location = new Point(81, 41);
|
||||
numericUpDownSpeed.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
|
||||
numericUpDownSpeed.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
|
||||
numericUpDownSpeed.Name = "numericUpDownSpeed";
|
||||
numericUpDownSpeed.Size = new Size(70, 23);
|
||||
numericUpDownSpeed.TabIndex = 2;
|
||||
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
|
||||
//
|
||||
// TextWeight
|
||||
//
|
||||
TextWeight.AutoSize = true;
|
||||
TextWeight.Location = new Point(17, 73);
|
||||
TextWeight.Name = "TextWeight";
|
||||
TextWeight.Size = new Size(48, 15);
|
||||
TextWeight.TabIndex = 1;
|
||||
TextWeight.Text = "Weight:";
|
||||
//
|
||||
// TextSpeed
|
||||
//
|
||||
TextSpeed.AutoSize = true;
|
||||
TextSpeed.Location = new Point(17, 43);
|
||||
TextSpeed.Name = "TextSpeed";
|
||||
TextSpeed.Size = new Size(42, 15);
|
||||
TextSpeed.TabIndex = 0;
|
||||
TextSpeed.Text = "Speed:";
|
||||
//
|
||||
// panelObject
|
||||
//
|
||||
panelObject.AllowDrop = true;
|
||||
panelObject.Controls.Add(pictureBoxObject);
|
||||
panelObject.Location = new Point(626, 56);
|
||||
panelObject.Name = "panelObject";
|
||||
panelObject.Size = new Size(325, 224);
|
||||
panelObject.TabIndex = 1;
|
||||
panelObject.DragDrop += PanelObject_DragDrop;
|
||||
panelObject.DragEnter += PanelObject_DragEnter;
|
||||
//
|
||||
// pictureBoxObject
|
||||
//
|
||||
pictureBoxObject.Location = new Point(20, 6);
|
||||
pictureBoxObject.Name = "pictureBoxObject";
|
||||
pictureBoxObject.Size = new Size(292, 218);
|
||||
pictureBoxObject.TabIndex = 11;
|
||||
pictureBoxObject.TabStop = false;
|
||||
//
|
||||
// labelAddColor
|
||||
//
|
||||
labelAddColor.AllowDrop = true;
|
||||
labelAddColor.BorderStyle = BorderStyle.FixedSingle;
|
||||
labelAddColor.Location = new Point(801, 7);
|
||||
labelAddColor.Name = "labelAddColor";
|
||||
labelAddColor.Size = new Size(150, 46);
|
||||
labelAddColor.TabIndex = 10;
|
||||
labelAddColor.Text = "Additional Color";
|
||||
labelAddColor.TextAlign = ContentAlignment.MiddleCenter;
|
||||
labelAddColor.DragDrop += LabelColor_DragDrop;
|
||||
labelAddColor.DragEnter += LabelColor_DragEnter;
|
||||
//
|
||||
// labelMainColor
|
||||
//
|
||||
labelMainColor.AllowDrop = true;
|
||||
labelMainColor.BorderStyle = BorderStyle.FixedSingle;
|
||||
labelMainColor.Location = new Point(626, 7);
|
||||
labelMainColor.Name = "labelMainColor";
|
||||
labelMainColor.Size = new Size(150, 46);
|
||||
labelMainColor.TabIndex = 9;
|
||||
labelMainColor.Text = "Main Color";
|
||||
labelMainColor.TextAlign = ContentAlignment.MiddleCenter;
|
||||
labelMainColor.DragDrop += LabelColor_DragDrop;
|
||||
labelMainColor.DragEnter += LabelColor_DragEnter;
|
||||
//
|
||||
// buttonOk
|
||||
//
|
||||
buttonOk.Location = new Point(626, 290);
|
||||
buttonOk.Name = "buttonOk";
|
||||
buttonOk.Size = new Size(135, 29);
|
||||
buttonOk.TabIndex = 2;
|
||||
buttonOk.Text = "Add";
|
||||
buttonOk.UseVisualStyleBackColor = true;
|
||||
buttonOk.Click += ButtonOk_Click;
|
||||
//
|
||||
// buttonCancel
|
||||
//
|
||||
buttonCancel.Location = new Point(816, 290);
|
||||
buttonCancel.Name = "buttonCancel";
|
||||
buttonCancel.Size = new Size(135, 29);
|
||||
buttonCancel.TabIndex = 3;
|
||||
buttonCancel.Text = "Cancel";
|
||||
buttonCancel.UseVisualStyleBackColor = true;
|
||||
//
|
||||
// FormLinerConfig
|
||||
//
|
||||
AutoScaleDimensions = new SizeF(7F, 15F);
|
||||
AutoScaleMode = AutoScaleMode.Font;
|
||||
ClientSize = new Size(985, 331);
|
||||
Controls.Add(buttonCancel);
|
||||
Controls.Add(labelAddColor);
|
||||
Controls.Add(buttonOk);
|
||||
Controls.Add(panelObject);
|
||||
Controls.Add(labelMainColor);
|
||||
Controls.Add(groupBoxParametrs);
|
||||
Name = "FormLinerConfig";
|
||||
Text = "FormLinerConfig";
|
||||
groupBoxParametrs.ResumeLayout(false);
|
||||
groupBoxParametrs.PerformLayout();
|
||||
groupBoxColors.ResumeLayout(false);
|
||||
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).EndInit();
|
||||
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).EndInit();
|
||||
panelObject.ResumeLayout(false);
|
||||
((System.ComponentModel.ISupportInitialize)pictureBoxObject).EndInit();
|
||||
ResumeLayout(false);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
private GroupBox groupBoxParametrs;
|
||||
private NumericUpDown numericUpDownWeight;
|
||||
private NumericUpDown numericUpDownSpeed;
|
||||
private Label TextWeight;
|
||||
private Label TextSpeed;
|
||||
private GroupBox groupBoxColors;
|
||||
private Panel panelBlue;
|
||||
private Panel panelGreen;
|
||||
private Panel panelRed;
|
||||
private CheckBox checkBoxDeck;
|
||||
private CheckBox checkBoxPool;
|
||||
private Panel panelPurple;
|
||||
private Panel panelBlack;
|
||||
private Panel panelGray;
|
||||
private Panel panelWhite;
|
||||
private Panel panelYellow;
|
||||
private Label labelSimpleObject;
|
||||
private Label labelModifiedObject;
|
||||
private Panel panelObject;
|
||||
private PictureBox pictureBoxObject;
|
||||
private Label labelAddColor;
|
||||
private Label labelMainColor;
|
||||
private Button buttonOk;
|
||||
private Button buttonCancel;
|
||||
}
|
||||
}
|
170
Liner/FormLinerConfig.cs
Normal file
170
Liner/FormLinerConfig.cs
Normal file
@ -0,0 +1,170 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Data;
|
||||
using System.Drawing;
|
||||
using System.Linq;
|
||||
using System.Reflection.Metadata.Ecma335;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
using Liner.Drawing;
|
||||
using Liner.Entities;
|
||||
|
||||
namespace Liner
|
||||
{
|
||||
/// <summary>
|
||||
/// Форма создания объекта
|
||||
/// </summary>
|
||||
public partial class FormLinerConfig : Form
|
||||
{
|
||||
/// <summary>
|
||||
/// Переменная-выбранная машина
|
||||
/// </summary>
|
||||
DrawingLiner? _liner = null;
|
||||
/// <summary>
|
||||
/// Событие
|
||||
/// </summary>
|
||||
private event Action<DrawingLiner>? EventAddLiner;
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
public FormLinerConfig()
|
||||
{
|
||||
InitializeComponent();
|
||||
panelBlack.MouseDown += PanelColor_MouseDown;
|
||||
panelPurple.MouseDown += PanelColor_MouseDown;
|
||||
panelGray.MouseDown += PanelColor_MouseDown;
|
||||
panelGreen.MouseDown += PanelColor_MouseDown;
|
||||
panelRed.MouseDown += PanelColor_MouseDown;
|
||||
panelWhite.MouseDown += PanelColor_MouseDown;
|
||||
panelYellow.MouseDown += PanelColor_MouseDown;
|
||||
panelBlue.MouseDown += PanelColor_MouseDown;
|
||||
buttonCancel.Click += (s, a) => Close();
|
||||
}
|
||||
/// <summary>
|
||||
/// Отрисовать лайнер
|
||||
/// </summary>
|
||||
private void DrawLiner()
|
||||
{
|
||||
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
|
||||
Graphics gr = Graphics.FromImage(bmp);
|
||||
_liner?.SetPosition(15, 15);
|
||||
_liner?.DrawTransport(gr);
|
||||
pictureBoxObject.Image = bmp;
|
||||
}
|
||||
/// <summary>
|
||||
/// Добавление события
|
||||
/// </summary>
|
||||
/// <param name="ev">Привязанный метод</param>
|
||||
public void AddEvent(Action<DrawingLiner> ev)
|
||||
{
|
||||
if (EventAddLiner == null)
|
||||
{
|
||||
EventAddLiner = ev;
|
||||
}
|
||||
else
|
||||
{
|
||||
EventAddLiner += ev;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Передаем информацию при нажатии на Label
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void LabelObject_MouseDown(object sender, MouseEventArgs e)
|
||||
{
|
||||
(sender as Label)?.DoDragDrop((sender as Label)?.Name, DragDropEffects.Move | DragDropEffects.Copy);
|
||||
}
|
||||
/// <summary>
|
||||
/// Проверка получаемой информации (ее типа на соответствие требуемому)
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void PanelObject_DragEnter(object sender, DragEventArgs e)
|
||||
{
|
||||
if (e.Data?.GetDataPresent(DataFormats.Text) ?? false)
|
||||
{
|
||||
e.Effect = DragDropEffects.Copy;
|
||||
}
|
||||
else
|
||||
{
|
||||
e.Effect = DragDropEffects.None;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Передаем информацию при нажатии на Panel с цветом
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void PanelColor_MouseDown(object sender, MouseEventArgs e)
|
||||
{
|
||||
(sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor, DragDropEffects.Move | DragDropEffects.Copy);
|
||||
}
|
||||
/// <summary>
|
||||
/// Действия при приеме перетаскиваемой информации
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void PanelObject_DragDrop(object sender, DragEventArgs e)
|
||||
{
|
||||
switch (e.Data?.GetData(DataFormats.Text).ToString())
|
||||
{
|
||||
case "labelSimpleObject":
|
||||
_liner = new DrawingLiner((int)numericUpDownSpeed.Value,
|
||||
(int)numericUpDownWeight.Value, Color.White, pictureBoxObject.Width,
|
||||
pictureBoxObject.Height);
|
||||
break;
|
||||
case "labelModifiedObject":
|
||||
_liner = new DrawingBigLiner((int)numericUpDownSpeed.Value,
|
||||
(int)numericUpDownWeight.Value, Color.White, Color.Black, checkBoxPool.Checked,
|
||||
checkBoxDeck.Checked, pictureBoxObject.Width, pictureBoxObject.Height);
|
||||
break;
|
||||
}
|
||||
|
||||
DrawLiner();
|
||||
}
|
||||
private void LabelColor_DragEnter(object sender, DragEventArgs e)
|
||||
{
|
||||
if (e.Data?.GetDataPresent(typeof(Color)) ?? false)
|
||||
{
|
||||
e.Effect = DragDropEffects.Copy;
|
||||
}
|
||||
else
|
||||
{
|
||||
e.Effect = DragDropEffects.None;
|
||||
}
|
||||
}
|
||||
private void LabelColor_DragDrop(object sender, DragEventArgs e)
|
||||
{
|
||||
if (_liner == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
switch (((Label)sender).Name)
|
||||
{
|
||||
case "labelMainColor":
|
||||
_liner.EntityLiner.BottomColor = (Color)e.Data.GetData(typeof(Color));
|
||||
break;
|
||||
case "labelAddColor":
|
||||
if (!(_liner is DrawingBigLiner))
|
||||
return;
|
||||
(_liner as DrawingBigLiner).SetAddColor((Color)e.Data.GetData(typeof(Color)));
|
||||
break;
|
||||
}
|
||||
DrawLiner();
|
||||
}
|
||||
/// <summary>
|
||||
/// Добавление лайнера
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void ButtonOk_Click(object sender, EventArgs e)
|
||||
{
|
||||
EventAddLiner?.Invoke(_liner);
|
||||
Close();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
64
Liner/Generics/DrawingLinerEqutables.cs
Normal file
64
Liner/Generics/DrawingLinerEqutables.cs
Normal file
@ -0,0 +1,64 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Liner.Drawing;
|
||||
using Liner.Entities;
|
||||
namespace Liner.Generics
|
||||
{
|
||||
internal class DrawingLinerEqutables : IEqualityComparer<DrawingLiner?>
|
||||
{
|
||||
public bool Equals(DrawingLiner? x, DrawingLiner? y)
|
||||
{
|
||||
if (x == null || x.EntityLiner == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(x));
|
||||
}
|
||||
if (y == null || y.EntityLiner == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(y));
|
||||
}
|
||||
if (x.GetType().Name != y.GetType().Name)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (x.EntityLiner.Speed != y.EntityLiner.Speed)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (x.EntityLiner.Weight != y.EntityLiner.Weight)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (x.EntityLiner.BottomColor != y.EntityLiner.BottomColor)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (x is DrawingBigLiner && y is DrawingBigLiner)
|
||||
{
|
||||
EntityBigLiner _LinerX = (EntityBigLiner)x.EntityLiner;
|
||||
EntityBigLiner _LinerY = (EntityBigLiner)y.EntityLiner;
|
||||
if (_LinerX.SwimmingPool != _LinerY.SwimmingPool)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (_LinerX.Deck != _LinerY.Deck)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (_LinerX.BodyColor != _LinerY.BodyColor)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
public int GetHashCode([DisallowNull] DrawingLiner obj)
|
||||
{
|
||||
return obj.GetHashCode();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
30
Liner/Generics/LinerCollectionInfo.cs
Normal file
30
Liner/Generics/LinerCollectionInfo.cs
Normal file
@ -0,0 +1,30 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Liner.Generics
|
||||
{
|
||||
public class LinerCollectionInfo : IEquatable<LinerCollectionInfo>
|
||||
{
|
||||
public string Name { get; private set; }
|
||||
public string Description { get; private set; }
|
||||
public LinerCollectionInfo(string name, string description)
|
||||
{
|
||||
Name = name;
|
||||
Description = description;
|
||||
}
|
||||
public bool Equals(LinerCollectionInfo? other)
|
||||
{
|
||||
if (Name == other?.Name)
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
public override int GetHashCode()
|
||||
{
|
||||
return Name.GetHashCode();
|
||||
}
|
||||
}
|
||||
}
|
44
Liner/Generics/LinerCompareByColor.cs
Normal file
44
Liner/Generics/LinerCompareByColor.cs
Normal file
@ -0,0 +1,44 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Liner.Entities;
|
||||
using Liner.Drawing;
|
||||
|
||||
namespace Liner.Generics
|
||||
{
|
||||
internal class LinerCompareByColor : IComparer<DrawingLiner?>
|
||||
{
|
||||
public int Compare(DrawingLiner? x, DrawingLiner? y)
|
||||
{
|
||||
if (x == null || x.EntityLiner == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(x));
|
||||
}
|
||||
if (y == null || y.EntityLiner == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(y));
|
||||
}
|
||||
var bottomColorCompare = x.EntityLiner.BottomColor.Name.CompareTo(y.EntityLiner.BottomColor.Name);
|
||||
if (bottomColorCompare != 0)
|
||||
{
|
||||
return bottomColorCompare;
|
||||
}
|
||||
if (x.EntityLiner is EntityBigLiner _entityBigLinerX && y.EntityLiner is EntityBigLiner _entityBigLinerY)
|
||||
{
|
||||
var bodyColorCompare = _entityBigLinerX.BodyColor.Name.CompareTo(_entityBigLinerY.BodyColor.Name);
|
||||
if (bodyColorCompare != 0)
|
||||
{
|
||||
return bodyColorCompare;
|
||||
}
|
||||
}
|
||||
var speedCompare = x.EntityLiner.Speed.CompareTo(y.EntityLiner.Speed);
|
||||
if (speedCompare != 0)
|
||||
{
|
||||
return speedCompare;
|
||||
}
|
||||
return x.EntityLiner.Weight.CompareTo(y.EntityLiner.Weight);
|
||||
}
|
||||
}
|
||||
}
|
34
Liner/Generics/LinerCompareByType.cs
Normal file
34
Liner/Generics/LinerCompareByType.cs
Normal file
@ -0,0 +1,34 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Liner.Drawing;
|
||||
using Liner.Entities;
|
||||
namespace Liner.Generics
|
||||
{
|
||||
internal class LinerCompareByType : IComparer<DrawingLiner?>
|
||||
{
|
||||
public int Compare(DrawingLiner? x, DrawingLiner? y)
|
||||
{
|
||||
if (x == null || x.EntityLiner == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(x));
|
||||
}
|
||||
if (y == null || y.EntityLiner == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(y));
|
||||
}
|
||||
if (x.GetType().Name != y.GetType().Name)
|
||||
{
|
||||
return x.GetType().Name.CompareTo(y.GetType().Name);
|
||||
}
|
||||
var speedCompare = x.EntityLiner.Speed.CompareTo(y.EntityLiner.Speed);
|
||||
if (speedCompare != 0)
|
||||
{
|
||||
return speedCompare;
|
||||
}
|
||||
return x.EntityLiner.Weight.CompareTo(y.EntityLiner.Weight);
|
||||
}
|
||||
}
|
||||
}
|
147
Liner/Generics/LinerGenericCollection.cs
Normal file
147
Liner/Generics/LinerGenericCollection.cs
Normal file
@ -0,0 +1,147 @@
|
||||
using Liner.MovingStrategies;
|
||||
using Liner.Drawing;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Liner.Generics
|
||||
{
|
||||
/// <summary>
|
||||
/// Параметризованный класс для набора объектов DrawningCar
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <typeparam name="U"></typeparam>
|
||||
public class LinerGenericCollection<T, U>
|
||||
where T : DrawingLiner
|
||||
where U : IMoveableObject
|
||||
{
|
||||
/// <summary>
|
||||
/// Ширина окна прорисовки
|
||||
/// </summary>
|
||||
private readonly int _pictureWidth;
|
||||
/// <summary>
|
||||
/// Высота окна прорисовки
|
||||
/// </summary>
|
||||
private readonly int _pictureHeight;
|
||||
/// <summary>
|
||||
/// Размер занимаемого объектом места (ширина)
|
||||
/// </summary>
|
||||
private readonly int _placeSizeWidth = 100;
|
||||
/// <summary>
|
||||
/// Размер занимаемого объектом места (высота)
|
||||
/// </summary>
|
||||
private readonly int _placeSizeHeight = 80;
|
||||
/// <summary>
|
||||
/// Набор объектов
|
||||
/// </summary>
|
||||
private readonly SetGeneric<T> _collection;
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
/// <param name="picWidth"></param>
|
||||
/// <param name="picHeight"></param>
|
||||
public LinerGenericCollection(int picWidth, int picHeight)
|
||||
{
|
||||
int width = picWidth / _placeSizeWidth;
|
||||
int height = picHeight / _placeSizeHeight;
|
||||
_pictureWidth = picWidth;
|
||||
_pictureHeight = picHeight;
|
||||
_collection = new SetGeneric<T>(width * height);
|
||||
}
|
||||
/// </summary>
|
||||
/// Получение объектов коллекции
|
||||
/// <summary>
|
||||
public IEnumerable<T?> GetLiners => _collection.GetLiners();
|
||||
/// <summary>
|
||||
/// Сортировка
|
||||
/// </summary>
|
||||
/// <param name="comparer"></param>
|
||||
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
|
||||
/// Перегрузка оператора сложения
|
||||
/// </summary>
|
||||
/// <param name="collect"></param>
|
||||
/// <param name="obj"></param>
|
||||
/// <returns></returns>
|
||||
public static int? operator +(LinerGenericCollection<T, U> collect, T? obj)
|
||||
{
|
||||
if (obj == null)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
return collect._collection.Insert(obj, new DrawingLinerEqutables());
|
||||
}
|
||||
/// <summary>
|
||||
/// Перегрузка оператора вычитания
|
||||
/// </summary>
|
||||
/// <param name="collect"></param>
|
||||
/// <param name="pos"></param>
|
||||
/// <returns></returns>
|
||||
public static bool operator -(LinerGenericCollection<T, U> collect, int pos)
|
||||
{
|
||||
if (collect._collection[pos] != null)
|
||||
{
|
||||
collect._collection.Remove(pos);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
/// <summary>
|
||||
/// Получение объекта IMoveableObject
|
||||
/// </summary>
|
||||
/// <param name="pos"></param>
|
||||
/// <returns></returns>
|
||||
public U? GetU(int pos)
|
||||
{
|
||||
return (U?)_collection[pos]?.GetMoveableObject;
|
||||
}
|
||||
/// <summary>
|
||||
/// Вывод всего набора объектов
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public Bitmap ShowLiners()
|
||||
{
|
||||
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; j++)
|
||||
{
|
||||
g.DrawRectangle(pen, i * _placeSizeWidth, j * _placeSizeHeight, _placeSizeWidth, _placeSizeHeight);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Метод прорисовки объектов
|
||||
/// </summary>
|
||||
/// <param name="g"></param>
|
||||
private void DrawObjects(Graphics g)
|
||||
{
|
||||
int iX = ((_pictureWidth / _placeSizeWidth) - 1) * _placeSizeWidth;
|
||||
int iY = 0;
|
||||
foreach (var liner in _collection.GetLiners())
|
||||
{
|
||||
liner?.SetPosition(iX, iY);
|
||||
liner?.DrawTransport(g);
|
||||
iX -= _placeSizeWidth;
|
||||
if (iX < 0)
|
||||
{
|
||||
iX = ((_pictureWidth / _placeSizeWidth) - 1) * _placeSizeWidth;
|
||||
iY += _placeSizeHeight;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
175
Liner/Generics/LinersGenericStorage.cs
Normal file
175
Liner/Generics/LinersGenericStorage.cs
Normal file
@ -0,0 +1,175 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Liner.Drawing;
|
||||
using Liner.MovingStrategies;
|
||||
namespace Liner.Generics
|
||||
{
|
||||
/// <summary>
|
||||
/// Класс для хранения коллекции
|
||||
/// </summary>
|
||||
public class LinersGenericStorage
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// Словарь (хранилище)
|
||||
/// </summary>
|
||||
readonly Dictionary<LinerCollectionInfo, LinerGenericCollection<DrawingLiner, DrawingObjectLiner>> _linerStorages;
|
||||
/// <summary>
|
||||
/// Возвращение списка названий наборов
|
||||
/// </summary>
|
||||
public List<LinerCollectionInfo> Keys => _linerStorages.Keys.ToList();
|
||||
/// <summary>
|
||||
/// Ширина окна отрисовки
|
||||
/// </summary>
|
||||
private readonly int _pictureWidth;
|
||||
/// <summary>
|
||||
/// Высота окна отрисовки
|
||||
/// </summary>
|
||||
private readonly int _pictureHeight;
|
||||
/// <summary>
|
||||
/// Разделитель для записи ключа и значения элемента словаря
|
||||
/// </summary>
|
||||
private static readonly char _separatorForKeyValue = '|';
|
||||
/// <summary>
|
||||
/// Разделитель для записей коллекции данных в файл
|
||||
/// </summary>
|
||||
private readonly char _separatorRecords = ';';
|
||||
/// <summary>
|
||||
/// Разделитель для записи информации по объекту в файл
|
||||
/// </summary>
|
||||
private static readonly char _separatorForObject = ':';
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
/// <param name="pictureWidth"></param>
|
||||
/// <param name="pictureHeight"></param>
|
||||
public LinersGenericStorage(int pictureWidth, int pictureHeight)
|
||||
{
|
||||
_linerStorages = new Dictionary<LinerCollectionInfo, LinerGenericCollection<DrawingLiner, DrawingObjectLiner>>();
|
||||
_pictureWidth = pictureWidth;
|
||||
_pictureHeight = pictureHeight;
|
||||
}
|
||||
/// <summary>
|
||||
/// Добавление набора
|
||||
/// </summary>
|
||||
/// <param name="name">Название набора</param>
|
||||
public void AddSet(string name)
|
||||
{
|
||||
if(_linerStorages.ContainsKey(new LinerCollectionInfo(name, string.Empty)))
|
||||
{
|
||||
return;
|
||||
}
|
||||
_linerStorages.Add(new LinerCollectionInfo(name, string.Empty), new LinerGenericCollection<DrawingLiner, DrawingObjectLiner>(_pictureWidth,_pictureHeight));
|
||||
}
|
||||
/// <summary>
|
||||
/// Удаление набора
|
||||
/// </summary>
|
||||
/// <param name="name">Название набора</param>
|
||||
public void DelSet(string name)
|
||||
{
|
||||
if (_linerStorages.ContainsKey(new LinerCollectionInfo(name, string.Empty)))
|
||||
{
|
||||
_linerStorages.Remove(new LinerCollectionInfo(name, string.Empty));
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Доступ к набору
|
||||
/// </summary>
|
||||
/// <param name="ind"></param>
|
||||
/// <returns></returns>
|
||||
public LinerGenericCollection<DrawingLiner, DrawingObjectLiner>? this[string ind]
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_linerStorages.ContainsKey(new LinerCollectionInfo(ind, string.Empty))) { return _linerStorages[new LinerCollectionInfo(ind, string.Empty)]; }
|
||||
return null;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Сохранение информации по лайнерам в хранилище в файл
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
File.Delete(filename);
|
||||
}
|
||||
StringBuilder data = new();
|
||||
foreach (KeyValuePair<LinerCollectionInfo,
|
||||
LinerGenericCollection<DrawingLiner, DrawingObjectLiner>> record in _linerStorages)
|
||||
{
|
||||
StringBuilder records = new();
|
||||
foreach (DrawingLiner? elem in record.Value.GetLiners)
|
||||
{
|
||||
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
|
||||
}
|
||||
data.AppendLine($"{record.Key.Name}{_separatorForKeyValue}{records}");
|
||||
}
|
||||
if (data.Length == 0)
|
||||
{
|
||||
throw new InvalidOperationException("Невалиданя операция, нет данных для сохранения");
|
||||
}
|
||||
string dataStr = data.ToString();
|
||||
using (StreamWriter writer = new StreamWriter(filename))
|
||||
{
|
||||
writer.WriteLine("LinerStorage");
|
||||
writer.WriteLine(dataStr);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Загрузка информации по автомобилям в хранилище из файла
|
||||
/// </summary>
|
||||
/// <param name="filename">Путь и имя файла</param>
|
||||
public void LoadData(string filename)
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
throw new FileNotFoundException("Файл не найден");
|
||||
}
|
||||
using (StreamReader reader = new StreamReader(filename))
|
||||
{
|
||||
string checker = reader.ReadLine();
|
||||
if (checker == null)
|
||||
{
|
||||
throw new NullReferenceException("Нет данных для загрузки");
|
||||
}
|
||||
if (!checker.StartsWith("LinerStorage"))
|
||||
{
|
||||
throw new FormatException("Неверный формат данных");
|
||||
}
|
||||
_linerStorages.Clear();
|
||||
string strs;
|
||||
while ((strs = reader.ReadLine()) != null) //переделал ужасную логику
|
||||
{
|
||||
if (strs == null)
|
||||
break;
|
||||
if (strs == string.Empty)
|
||||
break;
|
||||
string name = strs.Split('|')[0];
|
||||
LinerGenericCollection<DrawingLiner, DrawingObjectLiner> collection = new(_pictureWidth, _pictureHeight);
|
||||
foreach (string data in strs.Split('|')[1].Split(';').Reverse())
|
||||
{
|
||||
DrawingLiner? liner =
|
||||
data?.CreateDrawingLiner(_separatorForObject, _pictureWidth, _pictureHeight);
|
||||
if (liner != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
int? tmp = collection + liner;
|
||||
}
|
||||
catch (ApplicationException ex)
|
||||
{
|
||||
throw new ApplicationException($"Ошибка добавления в коллекцию: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
_linerStorages.Add(new LinerCollectionInfo(name, string.Empty), collection);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
134
Liner/Generics/SetGeneric.cs
Normal file
134
Liner/Generics/SetGeneric.cs
Normal file
@ -0,0 +1,134 @@
|
||||
using Liner.Exceptions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Liner.Generics
|
||||
{
|
||||
/// <summary>
|
||||
/// Параметризованный набор объектов
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public class SetGeneric<T>
|
||||
where T : class
|
||||
{
|
||||
/// <summary>
|
||||
/// Массив объектов, которые храним
|
||||
/// </summary>
|
||||
private readonly List<T?> _places;
|
||||
/// <summary>
|
||||
/// Количество объектов в массиве
|
||||
/// </summary>
|
||||
public int Count => _places.Capacity;
|
||||
/// <summary>
|
||||
/// Максимальное количество объектов в списке
|
||||
/// </summary>
|
||||
private readonly int _maxCount;
|
||||
/// <summary>
|
||||
/// Конструктор
|
||||
/// </summary>
|
||||
/// <param name="count"></param>
|
||||
public SetGeneric(int count)
|
||||
{
|
||||
_maxCount = count;
|
||||
_places = new List<T?>(count);
|
||||
}
|
||||
/// <summary>
|
||||
/// Добавление объекта в набор
|
||||
/// </summary>
|
||||
/// <param name="liner">Добавляемый лайнер</param>
|
||||
/// <returns></returns>
|
||||
public int Insert(T liner, IEqualityComparer<T?>? equal = null)
|
||||
{
|
||||
if (_places.Count >= _maxCount)
|
||||
{
|
||||
throw new StorageOverflowException(_places.Count);
|
||||
}
|
||||
return Insert(liner,0, equal);
|
||||
return 0;
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// Добавление объекта в набор на конкретную позицию
|
||||
/// </summary>
|
||||
/// <param name="liner">Добавляемый лайнер</param>
|
||||
/// <param name="position">Позиция</param>
|
||||
/// <returns></returns>
|
||||
public int Insert(T liner, int position, IEqualityComparer<T?>? equal = null)
|
||||
{
|
||||
if(_places.Count >= _maxCount)
|
||||
{
|
||||
throw new StorageOverflowException(_places.Count);
|
||||
}
|
||||
if(position < 0 || position > _places.Count)
|
||||
{
|
||||
throw new LinerNotFoundException(position);
|
||||
}
|
||||
if (equal != null && _places.Contains(liner, equal))
|
||||
{
|
||||
throw new ArgumentException("Этот объект уже существует в коллекции");
|
||||
}
|
||||
_places.Insert(position, liner);
|
||||
return position;
|
||||
}
|
||||
/// <summary>
|
||||
/// Удаление объекта из набора с конкретной позиции
|
||||
/// </summary>
|
||||
/// <param name="position"></param>
|
||||
/// <returns></returns>
|
||||
public bool Remove(int position)
|
||||
{
|
||||
if(_places.Count > position && position >= 0)
|
||||
{
|
||||
_places.RemoveAt(position);
|
||||
return true;
|
||||
}
|
||||
throw new LinerNotFoundException(position);
|
||||
}
|
||||
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
|
||||
/// <summary>
|
||||
/// Получение объекта из набора по позиции
|
||||
/// </summary>
|
||||
/// <param name="position"></param>
|
||||
/// <returns></returns>
|
||||
public T? this[int position]
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_places.Count > position && position >= 0)
|
||||
{
|
||||
return _places[position];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
set
|
||||
{
|
||||
try
|
||||
{
|
||||
Insert(value, position);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Проход по списку
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public IEnumerable<T?> GetLiners(int? maxLiners = null)
|
||||
{
|
||||
for (int i = 0; i < _places.Count; ++i)
|
||||
{
|
||||
yield return _places[i];
|
||||
if (maxLiners.HasValue && i == maxLiners.Value)
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -8,4 +8,42 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Remove="MovingStrategy\**" />
|
||||
<EmbeddedResource Remove="MovingStrategy\**" />
|
||||
<None Remove="MovingStrategy\**" />
|
||||
</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="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Configuration" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.EventLog" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.EventSource" Version="8.0.0" />
|
||||
<PackageReference Include="NLog" Version="5.2.7" />
|
||||
<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>
|
189
Liner/MainScreen.Designer.cs
generated
Normal file
189
Liner/MainScreen.Designer.cs
generated
Normal file
@ -0,0 +1,189 @@
|
||||
namespace Liner
|
||||
{
|
||||
partial class MainScreen : Form
|
||||
{
|
||||
/// <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()
|
||||
{
|
||||
pictureBoxLiner = new PictureBox();
|
||||
buttonCreateLiner = new Button();
|
||||
buttonUp = new Button();
|
||||
buttonDown = new Button();
|
||||
buttonLeft = new Button();
|
||||
buttonRight = new Button();
|
||||
buttonCreateBigLiner = new Button();
|
||||
comboBoxStrategy = new ComboBox();
|
||||
buttonStep = new Button();
|
||||
buttonSelectLiner = new Button();
|
||||
((System.ComponentModel.ISupportInitialize)pictureBoxLiner).BeginInit();
|
||||
SuspendLayout();
|
||||
//
|
||||
// pictureBoxLiner
|
||||
//
|
||||
pictureBoxLiner.Dock = DockStyle.Fill;
|
||||
pictureBoxLiner.Location = new Point(0, 0);
|
||||
pictureBoxLiner.Name = "pictureBoxLiner";
|
||||
pictureBoxLiner.Size = new Size(984, 661);
|
||||
pictureBoxLiner.SizeMode = PictureBoxSizeMode.AutoSize;
|
||||
pictureBoxLiner.TabIndex = 0;
|
||||
pictureBoxLiner.TabStop = false;
|
||||
//
|
||||
// buttonCreateLiner
|
||||
//
|
||||
buttonCreateLiner.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
|
||||
buttonCreateLiner.Location = new Point(34, 584);
|
||||
buttonCreateLiner.Name = "buttonCreateLiner";
|
||||
buttonCreateLiner.Size = new Size(87, 43);
|
||||
buttonCreateLiner.TabIndex = 1;
|
||||
buttonCreateLiner.Text = "Create Liner";
|
||||
buttonCreateLiner.UseVisualStyleBackColor = true;
|
||||
buttonCreateLiner.Click += buttonCreateLiner_Click;
|
||||
//
|
||||
// buttonUp
|
||||
//
|
||||
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
|
||||
buttonUp.BackgroundImage = Properties.Resources.arrowUp;
|
||||
buttonUp.BackgroundImageLayout = ImageLayout.Zoom;
|
||||
buttonUp.Location = new Point(865, 561);
|
||||
buttonUp.Name = "buttonUp";
|
||||
buttonUp.Size = new Size(30, 30);
|
||||
buttonUp.TabIndex = 2;
|
||||
buttonUp.UseVisualStyleBackColor = true;
|
||||
buttonUp.Click += buttonMove_Click;
|
||||
//
|
||||
// buttonDown
|
||||
//
|
||||
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
|
||||
buttonDown.BackgroundImage = Properties.Resources.arrowDown;
|
||||
buttonDown.BackgroundImageLayout = ImageLayout.Zoom;
|
||||
buttonDown.Location = new Point(865, 597);
|
||||
buttonDown.Name = "buttonDown";
|
||||
buttonDown.Size = new Size(30, 30);
|
||||
buttonDown.TabIndex = 3;
|
||||
buttonDown.UseVisualStyleBackColor = true;
|
||||
buttonDown.Click += buttonMove_Click;
|
||||
//
|
||||
// buttonLeft
|
||||
//
|
||||
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
|
||||
buttonLeft.BackgroundImage = Properties.Resources.arrowLeft;
|
||||
buttonLeft.BackgroundImageLayout = ImageLayout.Zoom;
|
||||
buttonLeft.Location = new Point(829, 597);
|
||||
buttonLeft.Name = "buttonLeft";
|
||||
buttonLeft.Size = new Size(30, 30);
|
||||
buttonLeft.TabIndex = 4;
|
||||
buttonLeft.UseVisualStyleBackColor = true;
|
||||
buttonLeft.Click += buttonMove_Click;
|
||||
//
|
||||
// buttonRight
|
||||
//
|
||||
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
|
||||
buttonRight.BackgroundImage = Properties.Resources.arrowRight;
|
||||
buttonRight.BackgroundImageLayout = ImageLayout.Zoom;
|
||||
buttonRight.Location = new Point(901, 597);
|
||||
buttonRight.Name = "buttonRight";
|
||||
buttonRight.Size = new Size(30, 30);
|
||||
buttonRight.TabIndex = 5;
|
||||
buttonRight.UseVisualStyleBackColor = true;
|
||||
buttonRight.Click += buttonMove_Click;
|
||||
//
|
||||
// buttonCreateBigLiner
|
||||
//
|
||||
buttonCreateBigLiner.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
|
||||
buttonCreateBigLiner.Location = new Point(127, 584);
|
||||
buttonCreateBigLiner.Name = "buttonCreateBigLiner";
|
||||
buttonCreateBigLiner.Size = new Size(87, 43);
|
||||
buttonCreateBigLiner.TabIndex = 6;
|
||||
buttonCreateBigLiner.Text = "Create BIG Liner";
|
||||
buttonCreateBigLiner.UseVisualStyleBackColor = true;
|
||||
buttonCreateBigLiner.Click += buttonCreateBigLiner_Click;
|
||||
//
|
||||
// comboBoxStrategy
|
||||
//
|
||||
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
|
||||
comboBoxStrategy.FormattingEnabled = true;
|
||||
comboBoxStrategy.Items.AddRange(new object[] { "MoveToCenter", "MoveToBorder" });
|
||||
comboBoxStrategy.Location = new Point(829, 12);
|
||||
comboBoxStrategy.Name = "comboBoxStrategy";
|
||||
comboBoxStrategy.Size = new Size(121, 23);
|
||||
comboBoxStrategy.TabIndex = 7;
|
||||
//
|
||||
// buttonStep
|
||||
//
|
||||
buttonStep.Location = new Point(856, 41);
|
||||
buttonStep.Name = "buttonStep";
|
||||
buttonStep.Size = new Size(75, 23);
|
||||
buttonStep.TabIndex = 8;
|
||||
buttonStep.Text = "Step";
|
||||
buttonStep.UseVisualStyleBackColor = true;
|
||||
buttonStep.Click += buttonStep_Click;
|
||||
//
|
||||
// buttonSelectLiner
|
||||
//
|
||||
buttonSelectLiner.Location = new Point(856, 93);
|
||||
buttonSelectLiner.Name = "buttonSelectLiner";
|
||||
buttonSelectLiner.Size = new Size(75, 23);
|
||||
buttonSelectLiner.TabIndex = 9;
|
||||
buttonSelectLiner.Text = "Select Liner";
|
||||
buttonSelectLiner.UseVisualStyleBackColor = true;
|
||||
buttonSelectLiner.Click += buttonSelectLiner_Click;
|
||||
//
|
||||
// MainScreen
|
||||
//
|
||||
AutoScaleDimensions = new SizeF(7F, 15F);
|
||||
AutoScaleMode = AutoScaleMode.Font;
|
||||
ClientSize = new Size(984, 661);
|
||||
Controls.Add(buttonSelectLiner);
|
||||
Controls.Add(buttonStep);
|
||||
Controls.Add(comboBoxStrategy);
|
||||
Controls.Add(buttonCreateBigLiner);
|
||||
Controls.Add(buttonRight);
|
||||
Controls.Add(buttonLeft);
|
||||
Controls.Add(buttonDown);
|
||||
Controls.Add(buttonUp);
|
||||
Controls.Add(buttonCreateLiner);
|
||||
Controls.Add(pictureBoxLiner);
|
||||
Name = "MainScreen";
|
||||
Text = "Liner";
|
||||
((System.ComponentModel.ISupportInitialize)pictureBoxLiner).EndInit();
|
||||
ResumeLayout(false);
|
||||
PerformLayout();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
private PictureBox pictureBoxLiner;
|
||||
private Button buttonCreateLiner;
|
||||
private Button buttonUp;
|
||||
private Button buttonDown;
|
||||
private Button buttonLeft;
|
||||
private Button buttonRight;
|
||||
private Button buttonCreateBigLiner;
|
||||
private ComboBox comboBoxStrategy;
|
||||
private Button buttonStep;
|
||||
private Button buttonSelectLiner;
|
||||
}
|
||||
}
|
154
Liner/MainScreen.cs
Normal file
154
Liner/MainScreen.cs
Normal file
@ -0,0 +1,154 @@
|
||||
using Liner.Drawing;
|
||||
using Liner.Entities;
|
||||
using Liner.MovingStrategies;
|
||||
using System.Drawing;
|
||||
|
||||
namespace Liner
|
||||
{
|
||||
public partial class MainScreen : Form
|
||||
{
|
||||
/// <summary>
|
||||
/// Ïîëå-îáúåêò äëÿ ïðîðèñîâêè îáúåêòà
|
||||
/// </summary>
|
||||
private DrawingLiner? _drawingLiner;
|
||||
private Bitmap bmp;
|
||||
/// <summary>
|
||||
/// Ñòðàòåãèÿ ïåðåìåùåíèÿ
|
||||
/// </summary>
|
||||
private AbstractStrategy? _abstractStrategy;
|
||||
/// <summary>
|
||||
/// Âûáðàííûé ëàéíåð
|
||||
/// </summary>
|
||||
public DrawingLiner? SelectedLiner { get; private set; }
|
||||
/// <summary>
|
||||
/// Èíèöèàëèçàöèÿ ôîðìû
|
||||
/// </summary>
|
||||
public MainScreen()
|
||||
{
|
||||
InitializeComponent();
|
||||
bmp = new(pictureBoxLiner.Width, pictureBoxLiner.Height);
|
||||
SelectedLiner = null;
|
||||
_abstractStrategy = null;
|
||||
}
|
||||
/// <summary>
|
||||
/// Ìåòîä ïðîðèñîâêè ëàéíåðà
|
||||
/// </summary>
|
||||
private void Draw()
|
||||
{
|
||||
if (_drawingLiner == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
Graphics gr = Graphics.FromImage(bmp);
|
||||
gr.Clear(Color.White);
|
||||
_drawingLiner.DrawTransport(gr);
|
||||
pictureBoxLiner.Image = bmp;
|
||||
}
|
||||
private void buttonCreateLiner_Click(object sender, EventArgs e)
|
||||
{
|
||||
Random random = new();
|
||||
Color mainColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
|
||||
Color addColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
|
||||
ColorDialog dialog = new();
|
||||
if (dialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
addColor = dialog.Color;
|
||||
}
|
||||
_drawingLiner = new DrawingLiner(random.Next(100, 300),
|
||||
random.Next(1000, 3000), mainColor,
|
||||
pictureBoxLiner.Width, pictureBoxLiner.Height);
|
||||
_drawingLiner.SetPosition(random.Next(10, 100), random.Next(10, 100));
|
||||
Draw();
|
||||
}
|
||||
|
||||
private void buttonMove_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (_drawingLiner == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
string name = ((Button)sender)?.Name ?? string.Empty;
|
||||
switch (name)
|
||||
{
|
||||
case "buttonUp":
|
||||
_drawingLiner.MoveTransport(DirectionType.Up);
|
||||
break;
|
||||
case "buttonDown":
|
||||
_drawingLiner.MoveTransport(DirectionType.Down);
|
||||
break;
|
||||
case "buttonLeft":
|
||||
_drawingLiner.MoveTransport(DirectionType.Left);
|
||||
break;
|
||||
case "buttonRight":
|
||||
_drawingLiner.MoveTransport(DirectionType.Right);
|
||||
break;
|
||||
}
|
||||
Draw();
|
||||
}
|
||||
|
||||
private void buttonCreateBigLiner_Click(object sender, EventArgs e)
|
||||
{
|
||||
Random random = new();
|
||||
Color mainColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
|
||||
Color addColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
|
||||
ColorDialog dialog = new();
|
||||
if (dialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
addColor = dialog.Color;
|
||||
}
|
||||
if (dialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
mainColor = dialog.Color;
|
||||
}
|
||||
_drawingLiner = new DrawingBigLiner(random.Next(100, 300),
|
||||
random.Next(1000, 3000), mainColor, addColor,
|
||||
Convert.ToBoolean(random.Next(0, 2)),
|
||||
Convert.ToBoolean(random.Next(1, 2)),
|
||||
pictureBoxLiner.Width, pictureBoxLiner.Height);
|
||||
_drawingLiner.SetPosition(random.Next(10, 100), random.Next(10, 100));
|
||||
Draw();
|
||||
}
|
||||
|
||||
private void buttonStep_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (_drawingLiner == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (comboBoxStrategy.Enabled)
|
||||
{
|
||||
_abstractStrategy = comboBoxStrategy.SelectedIndex
|
||||
switch
|
||||
{
|
||||
0 => new MoveToCenter(),
|
||||
1 => new MoveToBorder(),
|
||||
_ => null,
|
||||
};
|
||||
if (_abstractStrategy == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_abstractStrategy.SetData(new DrawingObjectLiner(_drawingLiner), pictureBoxLiner.Width,
|
||||
pictureBoxLiner.Height);
|
||||
comboBoxStrategy.Enabled = false;
|
||||
}
|
||||
if (_abstractStrategy == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_abstractStrategy.MakeStep();
|
||||
Draw();
|
||||
if (_abstractStrategy.GetStatus() == Status.Finish)
|
||||
{
|
||||
comboBoxStrategy.Enabled = true;
|
||||
_abstractStrategy = null;
|
||||
}
|
||||
}
|
||||
private void buttonSelectLiner_Click(object sender, EventArgs e)
|
||||
{
|
||||
SelectedLiner = _drawingLiner;
|
||||
DialogResult = DialogResult.OK;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
120
Liner/MainScreen.resx
Normal file
120
Liner/MainScreen.resx
Normal file
@ -0,0 +1,120 @@
|
||||
<?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>
|
||||
</root>
|
132
Liner/MovingStrategies/AbstractStrategy.cs
Normal file
132
Liner/MovingStrategies/AbstractStrategy.cs
Normal file
@ -0,0 +1,132 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Liner.MovingStrategies
|
||||
{
|
||||
/// <summary>
|
||||
/// Класс-стратегия перемещения объекта
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
39
Liner/MovingStrategies/DrawingObjectLiner.cs
Normal file
39
Liner/MovingStrategies/DrawingObjectLiner.cs
Normal file
@ -0,0 +1,39 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Liner.Drawing;
|
||||
|
||||
namespace Liner.MovingStrategies
|
||||
{
|
||||
/// <summary>
|
||||
/// Реализация интерфейса IMovableObject для работы с объектом DrawingLiner (паттерн Adapter)
|
||||
/// </summary>
|
||||
public class DrawingObjectLiner : IMoveableObject
|
||||
{
|
||||
private readonly DrawingLiner? _drawingLiner = null;
|
||||
public DrawingObjectLiner(DrawingLiner DrawingLiner)
|
||||
{
|
||||
_drawingLiner = DrawingLiner;
|
||||
}
|
||||
public ObjectParameters? GetObjectPosition
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_drawingLiner == null || _drawingLiner.EntityLiner == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return new ObjectParameters(_drawingLiner.GetPosX,
|
||||
_drawingLiner.GetPosY, _drawingLiner.GetWidth, _drawingLiner.GetHeight);
|
||||
}
|
||||
}
|
||||
public int GetStep => (int)(_drawingLiner?.EntityLiner?.Step ?? 0);
|
||||
public bool CheckCanMove(DirectionType direction) =>
|
||||
_drawingLiner?.CanMove(direction) ?? false;
|
||||
public void MoveObject(DirectionType direction) =>
|
||||
_drawingLiner?.MoveTransport(direction);
|
||||
}
|
||||
|
||||
}
|
34
Liner/MovingStrategies/IMoveableObject.cs
Normal file
34
Liner/MovingStrategies/IMoveableObject.cs
Normal file
@ -0,0 +1,34 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Liner.MovingStrategies
|
||||
{
|
||||
/// <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);
|
||||
}
|
||||
}
|
59
Liner/MovingStrategies/MoveToBorder.cs
Normal file
59
Liner/MovingStrategies/MoveToBorder.cs
Normal file
@ -0,0 +1,59 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Liner.MovingStrategies
|
||||
{
|
||||
/// <summary>
|
||||
/// Стратегия перемещения объекта в центр экрана
|
||||
/// </summary>
|
||||
public 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 = objParams.RightBorder - FieldWidth;
|
||||
if (Math.Abs(diffX) > GetStep())
|
||||
{
|
||||
if (diffX > 0)
|
||||
{
|
||||
MoveLeft();
|
||||
}
|
||||
else
|
||||
{
|
||||
MoveRight();
|
||||
}
|
||||
}
|
||||
var diffY = objParams.DownBorder - FieldHeight;
|
||||
if (Math.Abs(diffY) > GetStep())
|
||||
{
|
||||
if (diffY > 0)
|
||||
{
|
||||
MoveUp();
|
||||
}
|
||||
else
|
||||
{
|
||||
MoveDown();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
59
Liner/MovingStrategies/MoveToCenter.cs
Normal file
59
Liner/MovingStrategies/MoveToCenter.cs
Normal file
@ -0,0 +1,59 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Liner.MovingStrategies
|
||||
{
|
||||
/// <summary>
|
||||
/// Стратегия перемещения объекта в центр экрана
|
||||
/// </summary>
|
||||
public 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
57
Liner/MovingStrategies/ObjectParameters.cs
Normal file
57
Liner/MovingStrategies/ObjectParameters.cs
Normal file
@ -0,0 +1,57 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Liner.MovingStrategies
|
||||
{
|
||||
/// <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;
|
||||
}
|
||||
}
|
||||
}
|
18
Liner/MovingStrategies/Status.cs
Normal file
18
Liner/MovingStrategies/Status.cs
Normal file
@ -0,0 +1,18 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Liner.MovingStrategies
|
||||
{
|
||||
/// <summary>
|
||||
/// Статус выполнения операции перемещения
|
||||
/// </summary>
|
||||
public enum Status
|
||||
{
|
||||
NotInit,
|
||||
InProgress,
|
||||
Finish
|
||||
}
|
||||
}
|
@ -1,3 +1,10 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Windows.Forms;
|
||||
namespace Liner
|
||||
{
|
||||
internal static class Program
|
||||
@ -11,7 +18,28 @@ namespace Liner
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
ApplicationConfiguration.Initialize();
|
||||
Application.Run(new Form1());
|
||||
var services = new ServiceCollection();
|
||||
ConfigureServices(services);
|
||||
ApplicationConfiguration.Initialize();
|
||||
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
|
||||
{
|
||||
Application.Run(serviceProvider.GetRequiredService<FormLinerCollection>());
|
||||
}
|
||||
}
|
||||
private static void ConfigureServices(ServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<FormLinerCollection>().AddLogging(option =>
|
||||
{
|
||||
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}AppSettings.json", optional: false, reloadOnChange: true).Build();
|
||||
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
|
||||
option.AddSerilog(logger);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
103
Liner/Properties/Resources.Designer.cs
generated
Normal file
103
Liner/Properties/Resources.Designer.cs
generated
Normal file
@ -0,0 +1,103 @@
|
||||
//------------------------------------------------------------------------------
|
||||
// <auto-generated>
|
||||
// Этот код создан программой.
|
||||
// Исполняемая версия:4.0.30319.42000
|
||||
//
|
||||
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
|
||||
// повторной генерации кода.
|
||||
// </auto-generated>
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
namespace Liner.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("Liner.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 arrowDown {
|
||||
get {
|
||||
object obj = ResourceManager.GetObject("arrowDown", resourceCulture);
|
||||
return ((System.Drawing.Bitmap)(obj));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
|
||||
/// </summary>
|
||||
internal static System.Drawing.Bitmap arrowLeft {
|
||||
get {
|
||||
object obj = ResourceManager.GetObject("arrowLeft", resourceCulture);
|
||||
return ((System.Drawing.Bitmap)(obj));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
|
||||
/// </summary>
|
||||
internal static System.Drawing.Bitmap arrowRight {
|
||||
get {
|
||||
object obj = ResourceManager.GetObject("arrowRight", resourceCulture);
|
||||
return ((System.Drawing.Bitmap)(obj));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
|
||||
/// </summary>
|
||||
internal static System.Drawing.Bitmap arrowUp {
|
||||
get {
|
||||
object obj = ResourceManager.GetObject("arrowUp", resourceCulture);
|
||||
return ((System.Drawing.Bitmap)(obj));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
133
Liner/Properties/Resources.resx
Normal file
133
Liner/Properties/Resources.resx
Normal 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="arrowUp" type="System.Resources.ResXFileRef, System.Windows.Forms">
|
||||
<value>..\resources\arrowUp.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
|
||||
</data>
|
||||
<data name="arrowRight" type="System.Resources.ResXFileRef, System.Windows.Forms">
|
||||
<value>..\resources\arrowRight.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
|
||||
</data>
|
||||
<data name="arrowLeft" type="System.Resources.ResXFileRef, System.Windows.Forms">
|
||||
<value>..\resources\arrowLeft.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
|
||||
</data>
|
||||
<data name="arrowDown" type="System.Resources.ResXFileRef, System.Windows.Forms">
|
||||
<value>..\resources\arrowDown.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
|
||||
</data>
|
||||
</root>
|
BIN
Liner/resources/arrowDown.png
Normal file
BIN
Liner/resources/arrowDown.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 819 B |
BIN
Liner/resources/arrowLeft.png
Normal file
BIN
Liner/resources/arrowLeft.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 781 B |
BIN
Liner/resources/arrowRight.png
Normal file
BIN
Liner/resources/arrowRight.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 788 B |
BIN
Liner/resources/arrowUp.png
Normal file
BIN
Liner/resources/arrowUp.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 975 B |
Loading…
x
Reference in New Issue
Block a user