Compare commits

...

21 Commits
main ... Lab08

Author SHA1 Message Date
DyCTaTOR
a677485840 final 2023-12-17 21:10:48 +04:00
DyCTaTOR
73257bd563 Правки с наборами 2023-12-17 20:37:47 +04:00
DyCTaTOR
edd3626677 Ожидание правок 2023-12-14 18:46:20 +04:00
DyCTaTOR
3e9dddb1cd Мини-начало 2023-12-13 21:30:26 +04:00
DyCTaTOR
d5474b1357 На сдачу 2023-12-05 17:09:00 +04:00
DyCTaTOR
c2a8a8318e Правки1 2023-12-05 15:36:33 +04:00
DyCTaTOR
8253015db1 1 2023-12-04 22:01:53 +04:00
DyCTaTOR
a8c6ceef37 Начало 2023-12-04 22:01:10 +04:00
DyCTaTOR
dcb5a06f7f Правки 2023-11-22 10:50:20 +04:00
DyCTaTOR
215d2447dd Lab6 2023-11-21 12:52:09 +04:00
DyCTaTOR
5a00358b98 Лаб5 2023-11-20 22:38:04 +04:00
DyCTaTOR
f7a094b36b Начало1 2023-11-10 19:34:39 +04:00
DyCTaTOR
debf63ef08 правки 2023-11-07 14:22:31 +04:00
DyCTaTOR
5befb89c6b Lab4 2023-11-05 14:40:21 +04:00
DyCTaTOR
5c2d3d0465 правки лаб3 2023-10-25 10:41:39 +04:00
DyCTaTOR
358c3795cd Lab03 2023-10-25 10:40:23 +04:00
DyCTaTOR
39ab63f97c Лаб №2 2023-10-20 21:00:08 +04:00
DyCTaTOR
65d6622df9 Откат 2023-10-20 19:59:36 +04:00
DyCTaTOR
3bd364d6ab lab2 2023-10-11 10:05:42 +04:00
DyCTaTOR
b4a6ff06e9 PIbd-22. Stroev.V.M. Lab Work 01 2023-10-09 20:17:55 +04:00
DyCTaTOR
fe5a4700e3 Лабораторная 1 2023-10-09 20:05:16 +04:00
41 changed files with 3213 additions and 76 deletions

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Monorail
{
public enum DirectionType
{
Up = 1,
Down = 2,
Left = 3,
Right = 4
}
}

View File

@ -0,0 +1,160 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Monorail.Entities;
using Monorail.MovementStrategy;
namespace Monorail.DrawningObjects
{
public class DrawningMonorail
{
public EntityMonorail? EntityMonorail { get; protected set; }
public IMoveableObject GetMoveableObject => new DrawningObjectMonorail(this);
private int _pictureWidth;
private int _pictureHeight;
protected int _startPosX;
protected int _startPosY;
protected int _relWidth = 150;
protected readonly int _relHeight = 46;
public DrawningMonorail(int speed, double weight, Color bodyColor, int width, int height)
{
if (_relWidth >= width || _relHeight >= height)
{
return;
}
_pictureWidth = width;
_pictureHeight = height;
EntityMonorail = new EntityMonorail(speed, weight, bodyColor);
}
protected DrawningMonorail(int speed, double weight, Color bodyColor, int width,
int height, int carWidth, int carHeight)
{
if (_relWidth >= width || _relHeight >= height)
{
return;
}
_pictureWidth = width;
_pictureHeight = height;
_relWidth = carWidth;
_relHeight = carHeight;
EntityMonorail = new EntityMonorail(speed, weight, bodyColor);
}
public void SetPosition(int x, int y)
{
if (x < 0 || x > _pictureWidth - _relWidth)
{
x = 0;
}
if (y < 0 || y > _pictureHeight - _relHeight)
{
y = 0;
}
_startPosX = x;
_startPosY = y;
}
public void MoveTransport(DirectionType direction)
{
if (!CanMove(direction) || EntityMonorail == null)
{
return;
}
switch (direction)
{
case DirectionType.Left:
_startPosX -= (int)EntityMonorail.Step;
break;
case DirectionType.Right:
_startPosX += (int)EntityMonorail.Step;
break;
case DirectionType.Up:
_startPosY -= (int)EntityMonorail.Step;
break;
case DirectionType.Down:
_startPosY += (int)EntityMonorail.Step;
break;
}
}
public int GetPosX => _startPosX;
public int GetPosY => _startPosY;
public int GetWidth => _relWidth;
public int GetHeight => _relHeight;
public bool CanMove(DirectionType direction)
{
if (EntityMonorail == null)
{
return false;
}
return direction switch
{
DirectionType.Left => _startPosX - EntityMonorail.Step > 0,
DirectionType.Up => _startPosY - EntityMonorail.Step > 0,
DirectionType.Right => _startPosX + EntityMonorail.Step < _pictureWidth - _relWidth,
DirectionType.Down => _startPosY + EntityMonorail.Step < _pictureHeight - _relHeight
};
}
public virtual void DrawTransport(Graphics g)
{
if (EntityMonorail == null)
{
return;
}
_relWidth = 150;
Pen pen = new(Color.Black, 2);
Brush bodyBrush = new SolidBrush(EntityMonorail.BodyColor);
//колёса
g.DrawEllipse(pen, _startPosX + 20, _startPosY + 35, 15, 15);
g.DrawEllipse(pen, _startPosX + 50, _startPosY + 35, 15, 15);
g.DrawEllipse(pen, _startPosX + 80, _startPosY + 35, 15, 15);
g.DrawEllipse(pen, _startPosX + 110, _startPosY + 35, 15, 15);
g.DrawRectangle(pen, _startPosX + 22, _startPosY + 36, 40, 8);
g.DrawRectangle(pen, _startPosX + 82, _startPosY + 36, 40, 8);
g.DrawEllipse(pen, _startPosX + 3, _startPosY + 37, 30, 8);
g.DrawEllipse(pen, _startPosX + 110, _startPosY + 37, 29, 8);
Brush brBlack = new SolidBrush(Color.Black);
g.FillRectangle(brBlack, _startPosX + 22, _startPosY + 36, 40, 8);
g.FillRectangle(brBlack, _startPosX + 82, _startPosY + 36, 40, 8);
g.FillEllipse(brBlack, _startPosX + 3, _startPosY + 37, 30, 8);
g.FillEllipse(brBlack, _startPosX + 110, _startPosY + 37, 29, 8);
Brush brWhite = new SolidBrush(Color.White);
g.FillEllipse(brWhite, _startPosX + 20, _startPosY + 35, 15, 15);
g.FillEllipse(brWhite, _startPosX + 50, _startPosY + 35, 15, 15);
g.FillEllipse(brWhite, _startPosX + 80, _startPosY + 35, 15, 15);
g.FillEllipse(brWhite, _startPosX + 110, _startPosY + 35, 15, 15);
//Кабина
g.DrawRectangle(pen, _startPosX + 10, _startPosY + 20, 120, 16);
g.FillRectangle(bodyBrush, _startPosX + 10, _startPosY + 20, 120, 16);
Point p1 = new Point(_startPosX + 10, _startPosY + 20);
Point p2 = new Point(_startPosX + 130, _startPosY + 20);
Point p3 = new Point(_startPosX + 130, _startPosY + 5);
Point p4 = new Point(_startPosX + 13, _startPosY + 5);
g.DrawPolygon(pen, new Point[] { p1, p2, p3, p4 });
g.FillPolygon(bodyBrush, new Point[] { p1, p2, p3, p4 });
//дверь
g.FillRectangle(brWhite, _startPosX + 49, _startPosY + 9, 12, 22);
g.DrawRectangle(pen, _startPosX + 49, _startPosY + 9, 12, 22);
//Окна и прочее
Pen penBlue = new Pen(Color.Cyan, 2);
g.DrawRectangle(penBlue, _startPosX + 20, _startPosY + 8, 10, 10);
g.DrawRectangle(penBlue, _startPosX + 35, _startPosY + 8, 10, 10);
g.DrawRectangle(penBlue, _startPosX + 117, _startPosY + 8, 10, 10);
g.DrawRectangle(pen, _startPosX + 132, _startPosY + 10, 2, 22);
}
}
}

View File

@ -0,0 +1,100 @@
using Monorail.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Monorail.DrawningObjects
{
public class DrawningSecondMonorail : DrawningMonorail
{
public DrawningSecondMonorail(int speed, double weight, Color bodyColor, Color
additionalColor, bool monorails, bool secondCabin, int width, int height) :
base(speed, weight, bodyColor, width, height, 110, 60)
{
if (EntityMonorail != null)
{
EntityMonorail = new EntitySecondMonorail(speed, weight, bodyColor,
additionalColor, monorails, secondCabin);
}
}
public override void DrawTransport(Graphics g)
{
base.DrawTransport(g);
if (EntityMonorail is not EntitySecondMonorail secondMonorail)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(secondMonorail.AdditionalColor);
Brush brBlack = new SolidBrush(Color.Black);
Brush brWhite = new SolidBrush(Color.White);
Pen penBlue = new Pen(Color.Cyan, 2);
if (secondMonorail.Monorails)
{
g.DrawRectangle(pen, _startPosX, _startPosY + 50, 140, 10);
g.FillRectangle(brBlack, _startPosX, _startPosY + 50, 140, 10);
g.FillRectangle(brWhite, _startPosX + 5, _startPosY + 53, 130, 5);
}
if (secondMonorail.SecondCabin)
{
_relWidth = 290;
//низ
g.DrawEllipse(pen, _startPosX + 160, _startPosY + 35, 15, 15);
g.DrawEllipse(pen, _startPosX + 190, _startPosY + 35, 15, 15);
g.DrawEllipse(pen, _startPosX + 220, _startPosY + 35, 15, 15);
g.DrawEllipse(pen, _startPosX + 250, _startPosY + 35, 15, 15);
g.DrawRectangle(pen, _startPosX + 162, _startPosY + 36, 40, 8);
g.DrawRectangle(pen, _startPosX + 222, _startPosY + 36, 40, 8);
g.DrawEllipse(pen, _startPosX + 143, _startPosY + 37, 30, 8);
g.DrawEllipse(pen, _startPosX + 250, _startPosY + 37, 29, 8);
g.FillRectangle(brBlack, _startPosX + 162, _startPosY + 36, 40, 8);
g.FillRectangle(brBlack, _startPosX + 222, _startPosY + 36, 40, 8);
g.FillEllipse(brBlack, _startPosX + 143, _startPosY + 37, 30, 8);
g.FillEllipse(brBlack, _startPosX + 250, _startPosY + 37, 29, 8);
g.FillEllipse(brWhite, _startPosX + 160, _startPosY + 35, 15, 15);
g.FillEllipse(brWhite, _startPosX + 190, _startPosY + 35, 15, 15);
g.FillEllipse(brWhite, _startPosX + 220, _startPosY + 35, 15, 15);
g.FillEllipse(brWhite, _startPosX + 250, _startPosY + 35, 15, 15);
if (secondMonorail.Monorails)
{
g.DrawRectangle(pen, _startPosX + 140, _startPosY + 50, 145, 10);
g.FillRectangle(brBlack, _startPosX + 140, _startPosY + 50, 145, 10);
g.FillRectangle(brWhite, _startPosX + 135, _startPosY + 53, 145, 5);
}
//Кабина
g.DrawRectangle(pen, _startPosX + 150, _startPosY + 20, 120, 16);
g.FillRectangle(additionalBrush, _startPosX + 150, _startPosY + 20, 120, 16);
Point p5 = new Point(_startPosX + 150, _startPosY + 20);
Point p6 = new Point(_startPosX + 270, _startPosY + 20);
Point p7 = new Point(_startPosX + 267, _startPosY + 5);
Point p8 = new Point(_startPosX + 150, _startPosY + 5);
g.DrawPolygon(pen, new Point[] { p5, p6, p7, p8 });
g.FillPolygon(additionalBrush, new Point[] { p5, p6, p7, p8 });
//дверь
g.FillRectangle(brWhite, _startPosX + 189, _startPosY + 9, 12, 22);
g.DrawRectangle(pen, _startPosX + 189, _startPosY + 9, 12, 22);
//Окна и прочее
g.DrawRectangle(penBlue, _startPosX + 160, _startPosY + 8, 10, 10);
g.DrawRectangle(penBlue, _startPosX + 175, _startPosY + 8, 10, 10);
g.DrawRectangle(penBlue, _startPosX + 257, _startPosY + 8, 10, 10);
g.DrawRectangle(pen, _startPosX + 272, _startPosY + 10, 2, 22);
}
}
}
}

View File

@ -0,0 +1,52 @@
using Monorail.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Monorail.DrawningObjects
{
public static class ExtentionDrawningMonorail
{
public static DrawningMonorail? CreateDrawningMonorail(this string info,
char separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if(strs.Length == 3)
{
return new DrawningMonorail(Convert.ToInt32(strs[0]), Convert.ToInt32(strs[1]),
Color.FromName(strs[2]), width, height);
}
if (strs.Length == 7)
{
return new DrawningSecondMonorail(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]),
Color.FromName(strs[2]),
Color.FromName(strs[3]),
Convert.ToBoolean(strs[4]),
Convert.ToBoolean(strs[5]),
width, height);
}
return null;
}
public static string GetDataForSave(this DrawningMonorail drawningMonorail,
char separatorForObject)
{
var monorail = drawningMonorail.EntityMonorail;
if (monorail == null)
{
return string.Empty;
}
var str =
$"{monorail.Speed}{separatorForObject}{monorail.Weight}{separatorForObject}{monorail.BodyColor.Name}";
if (monorail is not EntitySecondMonorail secondMonorail)
{
return str;
}
return
$"{str}{separatorForObject}{secondMonorail.AdditionalColor.Name}{separatorForObject}" +
$"{secondMonorail.Monorails}{separatorForObject}{secondMonorail.SecondCabin}{separatorForObject}";
}
}
}

View File

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Monorail.Entities
{
public class EntityMonorail
{
public int Speed { get; private set; }
public double Weight { get; private set; }
public Color BodyColor { get; private set; }
public double Step => (double)Speed * 130 / Weight;
public EntityMonorail(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
public void setBodyColor(Color color)
{
BodyColor = color;
}
}
}

View File

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Monorail.Entities
{
public class EntitySecondMonorail : EntityMonorail
{
public Color AdditionalColor { get; private set; }
public bool Monorails { get; private set; }
public bool SecondCabin { get; private set; }
public EntitySecondMonorail(int speed, double weight, Color bodyColor,
Color additionalColor, bool monorails, bool secondCabin) : base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
Monorails = monorails;
SecondCabin = secondCabin;
}
public void setAdditionalColor(Color color)
{
AdditionalColor = color;
}
}
}

View File

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

View File

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

View File

@ -1,39 +0,0 @@
namespace Monorail
{
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()
{
this.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Text = "Form1";
}
#endregion
}
}

View File

@ -1,10 +0,0 @@
namespace Monorail
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}

198
Monorail/Monorail/FormMonorail.Designer.cs generated Normal file
View File

@ -0,0 +1,198 @@
namespace Monorail
{
partial class FormMonorail
{
/// <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()
{
pictureBoxMonorail = new PictureBox();
buttonUp = new Button();
buttonLeft = new Button();
buttonDown = new Button();
buttonRight = new Button();
ButtonCreateMonorail = new Button();
ButtonCreateSecondMonorail = new Button();
buttonStep = new Button();
comboBoxStrategy = new ComboBox();
button1 = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxMonorail).BeginInit();
SuspendLayout();
//
// pictureBoxMonorail
//
pictureBoxMonorail.Dock = DockStyle.Fill;
pictureBoxMonorail.Location = new Point(0, 0);
pictureBoxMonorail.Name = "pictureBoxMonorail";
pictureBoxMonorail.Size = new Size(882, 453);
pictureBoxMonorail.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBoxMonorail.TabIndex = 1;
pictureBoxMonorail.TabStop = false;
//
// buttonUp
//
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackColor = SystemColors.Info;
buttonUp.BackgroundImage = Properties.Resources.upper_arrow;
buttonUp.BackgroundImageLayout = ImageLayout.Zoom;
buttonUp.Location = new Point(784, 355);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(40, 40);
buttonUp.TabIndex = 6;
buttonUp.UseVisualStyleBackColor = false;
buttonUp.Click += buttonMove_Click;
//
// buttonLeft
//
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackColor = SystemColors.Info;
buttonLeft.BackgroundImage = Properties.Resources.left_arrow;
buttonLeft.BackgroundImageLayout = ImageLayout.Zoom;
buttonLeft.Location = new Point(738, 401);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(40, 40);
buttonLeft.TabIndex = 10;
buttonLeft.UseVisualStyleBackColor = false;
buttonLeft.Click += buttonMove_Click;
//
// buttonDown
//
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackColor = SystemColors.Info;
buttonDown.BackgroundImage = Properties.Resources.down_arrow;
buttonDown.BackgroundImageLayout = ImageLayout.Zoom;
buttonDown.Location = new Point(784, 401);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(40, 40);
buttonDown.TabIndex = 9;
buttonDown.UseVisualStyleBackColor = false;
buttonDown.Click += buttonMove_Click;
//
// buttonRight
//
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackColor = SystemColors.Info;
buttonRight.BackgroundImage = Properties.Resources.right_arrow;
buttonRight.BackgroundImageLayout = ImageLayout.Zoom;
buttonRight.Location = new Point(830, 401);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(40, 40);
buttonRight.TabIndex = 8;
buttonRight.UseVisualStyleBackColor = false;
buttonRight.Click += buttonMove_Click;
//
// ButtonCreateMonorail
//
ButtonCreateMonorail.BackColor = SystemColors.Info;
ButtonCreateMonorail.Location = new Point(9, 400);
ButtonCreateMonorail.Name = "ButtonCreateMonorail";
ButtonCreateMonorail.Size = new Size(175, 41);
ButtonCreateMonorail.TabIndex = 22;
ButtonCreateMonorail.Text = "Создать Монорельс";
ButtonCreateMonorail.UseVisualStyleBackColor = false;
ButtonCreateMonorail.Click += ButtonCreateMonorail_Click;
//
// ButtonCreateSecondMonorail
//
ButtonCreateSecondMonorail.BackColor = SystemColors.Info;
ButtonCreateSecondMonorail.Location = new Point(202, 400);
ButtonCreateSecondMonorail.Name = "ButtonCreateSecondMonorail";
ButtonCreateSecondMonorail.Size = new Size(239, 41);
ButtonCreateSecondMonorail.TabIndex = 21;
ButtonCreateSecondMonorail.Text = "Создать два Монорельса";
ButtonCreateSecondMonorail.UseVisualStyleBackColor = false;
ButtonCreateSecondMonorail.Click += ButtonCreateSecondMonorail_Click;
//
// buttonStep
//
buttonStep.BackColor = SystemColors.Info;
buttonStep.Location = new Point(782, 43);
buttonStep.Name = "buttonStep";
buttonStep.Size = new Size(94, 29);
buttonStep.TabIndex = 20;
buttonStep.Text = "Шаг";
buttonStep.UseVisualStyleBackColor = false;
buttonStep.Click += ButtonStep_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.BackColor = SystemColors.Info;
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "0", "1" });
comboBoxStrategy.Location = new Point(725, 9);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(151, 28);
comboBoxStrategy.TabIndex = 19;
//
// button1
//
button1.BackColor = SystemColors.Info;
button1.Location = new Point(710, 88);
button1.Name = "button1";
button1.Size = new Size(166, 40);
button1.TabIndex = 23;
button1.Text = "Выбрать Монорельс";
button1.UseVisualStyleBackColor = false;
button1.Click += ButtonSelectMonorail_Click;
//
// FormMonorail
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
BackColor = SystemColors.ControlDarkDark;
ClientSize = new Size(882, 453);
Controls.Add(button1);
Controls.Add(ButtonCreateMonorail);
Controls.Add(ButtonCreateSecondMonorail);
Controls.Add(buttonStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonLeft);
Controls.Add(buttonDown);
Controls.Add(buttonRight);
Controls.Add(buttonUp);
Controls.Add(pictureBoxMonorail);
Name = "FormMonorail";
StartPosition = FormStartPosition.CenterScreen;
Text = "Monorail";
((System.ComponentModel.ISupportInitialize)pictureBoxMonorail).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private PictureBox pictureBoxMonorail;
private Button buttonUp;
private Button buttonLeft;
private Button buttonDown;
private Button buttonRight;
private Button ButtonCreateMonorail;
private Button ButtonCreateSecondMonorail;
private Button buttonStep;
private ComboBox comboBoxStrategy;
private Button button1;
}
}

View File

@ -0,0 +1,141 @@
using Monorail.DrawningObjects;
using Monorail.MovementStrategy;
using System.Drawing;
namespace Monorail
{
public partial class FormMonorail : Form
{
private DrawningMonorail? _drawningMonorail;
private AbstractStrategy? _abstractStrategy;
public DrawningMonorail? SelectedMonorail { get; private set; }
public FormMonorail()
{
InitializeComponent();
_abstractStrategy = null;
SelectedMonorail = null;
}
private void Draw()
{
if (_drawningMonorail == null)
{
return;
}
Bitmap bmp = new(pictureBoxMonorail.Width,
pictureBoxMonorail.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningMonorail.DrawTransport(gr);
pictureBoxMonorail.Image = bmp;
}
private void ButtonCreateSecondMonorail_Click(object sender, EventArgs e)
{
Random random = new();
Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256),
random.Next(0, 256));
ColorDialog dialog1 = new();
if (dialog1.ShowDialog() == DialogResult.OK)
{
color = dialog1.Color;
}
Color dopColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256),
random.Next(0, 256));
ColorDialog dialog2 = new();
if (dialog2.ShowDialog() == DialogResult.OK)
{
dopColor = dialog2.Color;
}
_drawningMonorail = new DrawningSecondMonorail(random.Next(100, 300),
random.Next(1000, 3000), color, dopColor,
true, true,
pictureBoxMonorail.Width, pictureBoxMonorail.Height);
_drawningMonorail.SetPosition(random.Next(10, 100), random.Next(10,
100));
Draw();
}
private void ButtonCreateMonorail_Click(object sender, EventArgs e)
{
Random random = new();
Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256),
random.Next(0, 256));
ColorDialog dialog1 = new();
if (dialog1.ShowDialog() == DialogResult.OK)
{
color = dialog1.Color;
}
_drawningMonorail = new DrawningMonorail(random.Next(100, 300),
random.Next(1000, 3000), color, pictureBoxMonorail.Width, pictureBoxMonorail.Height);
_drawningMonorail.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
private void buttonMove_Click(object sender, EventArgs e)
{
if (_drawningMonorail == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
switch (name)
{
case "buttonUp":
_drawningMonorail.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
_drawningMonorail.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
_drawningMonorail.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
_drawningMonorail.MoveTransport(DirectionType.Right);
break;
}
Draw();
}
private void ButtonStep_Click(object sender, EventArgs e)
{
if (_drawningMonorail == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_abstractStrategy = comboBoxStrategy.SelectedIndex
switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(new
DrawningObjectMonorail(_drawningMonorail), pictureBoxMonorail.Width,
pictureBoxMonorail.Height);
}
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_abstractStrategy = null;
}
}
private void ButtonSelectMonorail_Click(object sender, EventArgs e)
{
SelectedMonorail = _drawningMonorail;
DialogResult = DialogResult.OK;
}
}
}

View File

@ -1,24 +1,24 @@
<?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
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="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>
@ -26,36 +26,36 @@
<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
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
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
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
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
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
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
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->

View File

@ -0,0 +1,301 @@
namespace Monorail
{
partial class FormMonorailCollection
{
/// <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()
{
pictureBoxCollection = new PictureBox();
panel1 = new Panel();
ButtonSortByColor = new Button();
ButtonSortByType = new Button();
panel2 = new Panel();
label2 = new Label();
listBoxStorages = new ListBox();
textBoxStorageName = new TextBox();
button1 = new Button();
ButtonAddObject = new Button();
maskedTextBoxNumber = new TextBox();
buttonRefreshCol = new Button();
buttonDelMonorail = new Button();
buttonAddMonorail = new Button();
label1 = new Label();
menuStrip1 = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
сохранитьToolStripMenuItem = new ToolStripMenuItem();
загрузитьToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
panel1.SuspendLayout();
panel2.SuspendLayout();
menuStrip1.SuspendLayout();
SuspendLayout();
//
// pictureBoxCollection
//
pictureBoxCollection.Location = new Point(5, 31);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(1017, 485);
pictureBoxCollection.TabIndex = 5;
pictureBoxCollection.TabStop = false;
//
// panel1
//
panel1.BackColor = SystemColors.Info;
panel1.Controls.Add(ButtonSortByColor);
panel1.Controls.Add(ButtonSortByType);
panel1.Controls.Add(panel2);
panel1.Controls.Add(maskedTextBoxNumber);
panel1.Controls.Add(buttonRefreshCol);
panel1.Controls.Add(buttonDelMonorail);
panel1.Controls.Add(buttonAddMonorail);
panel1.Controls.Add(label1);
panel1.Location = new Point(1025, -1);
panel1.Name = "panel1";
panel1.Size = new Size(204, 517);
panel1.TabIndex = 4;
//
// ButtonSortByColor
//
ButtonSortByColor.Font = new Font("Segoe UI", 7.8F, FontStyle.Regular, GraphicsUnit.Point);
ButtonSortByColor.Location = new Point(12, 293);
ButtonSortByColor.Name = "ButtonSortByColor";
ButtonSortByColor.Size = new Size(179, 41);
ButtonSortByColor.TabIndex = 9;
ButtonSortByColor.Text = "Сортировка по цвету";
ButtonSortByColor.UseVisualStyleBackColor = true;
ButtonSortByColor.Click += ButtonSortByColor_Click;
//
// ButtonSortByType
//
ButtonSortByType.Font = new Font("Segoe UI", 7.8F, FontStyle.Regular, GraphicsUnit.Point);
ButtonSortByType.Location = new Point(12, 246);
ButtonSortByType.Name = "ButtonSortByType";
ButtonSortByType.Size = new Size(179, 41);
ButtonSortByType.TabIndex = 8;
ButtonSortByType.Text = "Сортировка по типу";
ButtonSortByType.UseVisualStyleBackColor = true;
ButtonSortByType.Click += ButtonSortByType_Click;
//
// panel2
//
panel2.Controls.Add(label2);
panel2.Controls.Add(listBoxStorages);
panel2.Controls.Add(textBoxStorageName);
panel2.Controls.Add(button1);
panel2.Controls.Add(ButtonAddObject);
panel2.Location = new Point(12, 20);
panel2.Name = "panel2";
panel2.Size = new Size(179, 209);
panel2.TabIndex = 7;
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(3, -3);
label2.Name = "label2";
label2.Size = new Size(66, 20);
label2.TabIndex = 8;
label2.Text = "Наборы";
//
// listBoxStorages
//
listBoxStorages.FormattingEnabled = true;
listBoxStorages.ItemHeight = 20;
listBoxStorages.Location = new Point(17, 85);
listBoxStorages.Name = "listBoxStorages";
listBoxStorages.Size = new Size(144, 84);
listBoxStorages.TabIndex = 9;
listBoxStorages.Click += ListBoxObjects_SelectedIndexChanged;
//
// textBoxStorageName
//
textBoxStorageName.Location = new Point(17, 20);
textBoxStorageName.Name = "textBoxStorageName";
textBoxStorageName.Size = new Size(143, 27);
textBoxStorageName.TabIndex = 8;
//
// button1
//
button1.Font = new Font("Segoe UI", 7.8F, FontStyle.Regular, GraphicsUnit.Point);
button1.Location = new Point(16, 174);
button1.Name = "button1";
button1.Size = new Size(143, 26);
button1.TabIndex = 5;
button1.Text = "Удалить набор";
button1.UseVisualStyleBackColor = true;
button1.Click += ButtonDelObject_Click;
//
// ButtonAddObject
//
ButtonAddObject.Font = new Font("Segoe UI", 7.8F, FontStyle.Regular, GraphicsUnit.Point);
ButtonAddObject.Location = new Point(18, 51);
ButtonAddObject.Name = "ButtonAddObject";
ButtonAddObject.Size = new Size(143, 27);
ButtonAddObject.TabIndex = 6;
ButtonAddObject.Text = "Добавить набор";
ButtonAddObject.UseVisualStyleBackColor = true;
ButtonAddObject.Click += ButtonAddObject_Click;
//
// maskedTextBoxNumber
//
maskedTextBoxNumber.Location = new Point(30, 387);
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(125, 27);
maskedTextBoxNumber.TabIndex = 4;
//
// buttonRefreshCol
//
buttonRefreshCol.Font = new Font("Segoe UI", 7.8F, FontStyle.Regular, GraphicsUnit.Point);
buttonRefreshCol.Location = new Point(12, 466);
buttonRefreshCol.Name = "buttonRefreshCol";
buttonRefreshCol.Size = new Size(179, 41);
buttonRefreshCol.TabIndex = 3;
buttonRefreshCol.Text = "Обновить коллекцию";
buttonRefreshCol.UseVisualStyleBackColor = true;
buttonRefreshCol.Click += ButtonRefreshCollection_Click;
//
// buttonDelMonorail
//
buttonDelMonorail.Font = new Font("Segoe UI", 7.8F, FontStyle.Regular, GraphicsUnit.Point);
buttonDelMonorail.Location = new Point(12, 418);
buttonDelMonorail.Name = "buttonDelMonorail";
buttonDelMonorail.Size = new Size(179, 41);
buttonDelMonorail.TabIndex = 2;
buttonDelMonorail.Text = "Удалить монорельс";
buttonDelMonorail.UseVisualStyleBackColor = true;
buttonDelMonorail.Click += ButtonRemoveMonorail_Click;
//
// buttonAddMonorail
//
buttonAddMonorail.Font = new Font("Segoe UI", 7.8F, FontStyle.Regular, GraphicsUnit.Point);
buttonAddMonorail.Location = new Point(12, 340);
buttonAddMonorail.Name = "buttonAddMonorail";
buttonAddMonorail.Size = new Size(179, 41);
buttonAddMonorail.TabIndex = 1;
buttonAddMonorail.Text = "Добавить монорельс";
buttonAddMonorail.UseVisualStyleBackColor = true;
buttonAddMonorail.Click += ButtonAddMonorail_Click;
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(3, -3);
label1.Name = "label1";
label1.Size = new Size(103, 20);
label1.TabIndex = 0;
label1.Text = "Инструменты";
//
// menuStrip1
//
menuStrip1.ImageScalingSize = new Size(20, 20);
menuStrip1.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new Size(1228, 28);
menuStrip1.TabIndex = 6;
menuStrip1.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { сохранитьToolStripMenuItem, загрузитьToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(59, 24);
файлToolStripMenuItem.Text = "Файл";
//
// сохранитьToolStripMenuItem
//
сохранитьToolStripMenuItem.Name = "сохранитьToolStripMenuItem";
сохранитьToolStripMenuItem.Size = new Size(166, 26);
сохранитьToolStripMenuItem.Text = "Сохранить";
сохранитьToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// загрузитьToolStripMenuItem
//
загрузитьToolStripMenuItem.Name = агрузитьToolStripMenuItem";
загрузитьToolStripMenuItem.Size = new Size(166, 26);
загрузитьToolStripMenuItem.Text = "Загрузить";
загрузитьToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog";
openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
saveFileDialog.FileName = "saveFileDialog";
saveFileDialog.Filter = "txt file | *.txt";
//
// FormMonorailCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
BackColor = SystemColors.ControlDarkDark;
ClientSize = new Size(1228, 518);
Controls.Add(pictureBoxCollection);
Controls.Add(panel1);
Controls.Add(menuStrip1);
MainMenuStrip = menuStrip1;
Name = "FormMonorailCollection";
Text = "Набор Монорельсов";
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
panel1.ResumeLayout(false);
panel1.PerformLayout();
panel2.ResumeLayout(false);
panel2.PerformLayout();
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
private PictureBox pictureBoxCollection;
private Panel panel1;
private Button buttonRefreshCol;
private Button buttonDelMonorail;
private Button buttonAddMonorail;
private Label label1;
private TextBox maskedTextBoxNumber;
private Button button1;
private Panel panel2;
private Label label2;
private ListBox listBoxStorages;
private TextBox textBoxStorageName;
private Button ButtonAddObject;
private MenuStrip menuStrip1;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem сохранитьToolStripMenuItem;
private ToolStripMenuItem загрузитьToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Button ButtonSortByColor;
private Button ButtonSortByType;
}
}

View File

@ -0,0 +1,262 @@
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 Monorail.DrawningObjects;
using Monorail.Exceptions;
using Monorail.Generics;
using Monorail.MovementStrategy;
using Monorail.Exceptions;
using Microsoft.Extensions.Logging;
using System.Xml.Linq;
namespace Monorail
{
public partial class FormMonorailCollection : Form
{
private readonly MonorailsGenericStorage _storage;
private readonly ILogger _logger;
readonly int countPlace = 22;
private void ButtonSortByType_Click(object sender, EventArgs e) =>
CompareMonorails(new MonorailCompareByType());
private void ButtonSortByColor_Click(object sender, EventArgs e) =>
CompareMonorails(new MonorailCompareByColor());
public FormMonorailCollection(ILogger<FormMonorailCollection> logger)
{
InitializeComponent();
_storage = new MonorailsGenericStorage
(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
}
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 ButtonAddObject_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxStorageName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Не все данные заполнены");
return;
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
_logger.LogInformation($"Добавлен набор:{textBoxStorageName.Text}");
}
private void ListBoxObjects_SelectedIndexChanged(object sender,
EventArgs e)
{
pictureBoxCollection.Image =
_storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowMonorails();
}
private void CompareMonorails(IComparer<DrawningMonorail?> comparer)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
obj.Sort(comparer);
pictureBoxCollection.Image = obj.ShowMonorails();
}
private void ButtonDelObject_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Удалить объект{name}?",
"Удаление", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(name);
ReloadObjects();
_logger.LogInformation($"Удален набор: {name}");
}
}
private void ButtonAddMonorail_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
var formMonorailConfig = new FormMonorailConfig();
formMonorailConfig.AddEvent(AddMonorail);
formMonorailConfig.Show();
}
private void AddMonorail(DrawningMonorail monorail)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
try
{
int addedIndex = obj + monorail;
if (addedIndex != -1 && addedIndex < countPlace)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowMonorails();
_logger.LogInformation($"Добавлен монорельс");
}
}
catch (StorageOverflowException ex)
{
MessageBox.Show(ex.Message, "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning(ex.Message);
}
catch (ArgumentException)
{
MessageBox.Show("Такой монорельс уже существует", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Такой монорельс уже существует");
}
}
private void ButtonRemoveMonorail_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = 0;
try
{
pos = Convert.ToInt32(maskedTextBoxNumber.Text);
}
catch (Exception)
{
MessageBox.Show("Введите позицию монорельса", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
var curObj = obj - pos;
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowMonorails();
_logger.LogInformation($"Объект удален по позиции: {pos}");
}
catch (MonorailNotFoundException ex)
{
MessageBox.Show(ex.Message, "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не удалось удалить объект по позиции {pos}");
}
}
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
pictureBoxCollection.Image = obj.ShowMonorails();
}
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение файла");
}
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);
MessageBox.Show("Загрузка прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadObjects();
_logger.LogInformation("Загрузка файла");
}
catch (Exception ex)
{
MessageBox.Show($"Не загрузилось. {ex.Message}",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не загрузилось: {ex.Message}");
}
}
}
}
}

View 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="menuStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>330, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>176, 17</value>
</metadata>
</root>

View File

@ -0,0 +1,399 @@
namespace Monorail
{
partial class FormMonorailConfig
{
/// <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()
{
groupBox1 = new GroupBox();
ButtonOk = new Button();
ButtonCancel = new Button();
label_body_color = new Label();
label_additional_color = new Label();
labelModifiedObject = new Label();
labelSimpleObject = new Label();
GroupColor = new GroupBox();
panelPurple = new Panel();
panelYellow = new Panel();
panelBlack = new Panel();
panelBlue = new Panel();
panelGray = new Panel();
panelGreen = new Panel();
panelWhite = new Panel();
panelRed = new Panel();
checkBoxSecondCabin = new CheckBox();
checkBoxReil = new CheckBox();
label2 = new Label();
label1 = new Label();
numericUpDownWeight = new NumericUpDown();
numericUpDownSpeed = new NumericUpDown();
pictureBoxObject = new PictureBox();
label4 = new Label();
PanelObject = new Panel();
groupBox1.SuspendLayout();
GroupColor.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
PanelObject.SuspendLayout();
SuspendLayout();
//
// groupBox1
//
groupBox1.Controls.Add(ButtonOk);
groupBox1.Controls.Add(ButtonCancel);
groupBox1.Controls.Add(label_body_color);
groupBox1.Controls.Add(label_additional_color);
groupBox1.Controls.Add(labelModifiedObject);
groupBox1.Controls.Add(labelSimpleObject);
groupBox1.Controls.Add(GroupColor);
groupBox1.Controls.Add(checkBoxSecondCabin);
groupBox1.Controls.Add(checkBoxReil);
groupBox1.Controls.Add(label2);
groupBox1.Controls.Add(label1);
groupBox1.Controls.Add(numericUpDownWeight);
groupBox1.Controls.Add(numericUpDownSpeed);
groupBox1.ForeColor = SystemColors.ControlLightLight;
groupBox1.Location = new Point(12, 12);
groupBox1.Name = "groupBox1";
groupBox1.Size = new Size(421, 540);
groupBox1.TabIndex = 0;
groupBox1.TabStop = false;
groupBox1.Text = "Параметры";
//
// ButtonOk
//
ButtonOk.BackColor = SystemColors.Info;
ButtonOk.ForeColor = SystemColors.ControlText;
ButtonOk.Location = new Point(313, 480);
ButtonOk.Name = "ButtonOk";
ButtonOk.Size = new Size(101, 46);
ButtonOk.TabIndex = 12;
ButtonOk.Text = "Добавить";
ButtonOk.UseVisualStyleBackColor = false;
ButtonOk.Click += ButtonOk_Click;
//
// ButtonCancel
//
ButtonCancel.BackColor = SystemColors.Info;
ButtonCancel.ForeColor = SystemColors.ControlText;
ButtonCancel.Location = new Point(6, 480);
ButtonCancel.Name = "ButtonCancel";
ButtonCancel.Size = new Size(106, 46);
ButtonCancel.TabIndex = 13;
ButtonCancel.Text = "Отмена";
ButtonCancel.UseVisualStyleBackColor = false;
//
// label_body_color
//
label_body_color.AllowDrop = true;
label_body_color.BackColor = SystemColors.Info;
label_body_color.BorderStyle = BorderStyle.FixedSingle;
label_body_color.ForeColor = SystemColors.ControlText;
label_body_color.Location = new Point(6, 382);
label_body_color.Name = "label_body_color";
label_body_color.Size = new Size(106, 56);
label_body_color.TabIndex = 10;
label_body_color.Text = "Осн. цвет";
label_body_color.TextAlign = ContentAlignment.MiddleCenter;
label_body_color.DragDrop += PanelColor_DragDrop;
label_body_color.DragEnter += PanelColor_DragEnter;
//
// label_additional_color
//
label_additional_color.AllowDrop = true;
label_additional_color.BackColor = SystemColors.Info;
label_additional_color.BorderStyle = BorderStyle.FixedSingle;
label_additional_color.ForeColor = SystemColors.ControlText;
label_additional_color.Location = new Point(250, 382);
label_additional_color.Name = "label_additional_color";
label_additional_color.Size = new Size(101, 56);
label_additional_color.TabIndex = 10;
label_additional_color.Text = "Доп. цвет";
label_additional_color.TextAlign = ContentAlignment.MiddleCenter;
label_additional_color.DragDrop += PanelColor_DragDrop;
label_additional_color.DragEnter += PanelColor_DragEnter;
//
// labelModifiedObject
//
labelModifiedObject.AllowDrop = true;
labelModifiedObject.BackColor = SystemColors.Info;
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.ForeColor = SystemColors.ControlText;
labelModifiedObject.Location = new Point(264, 118);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(150, 70);
labelModifiedObject.TabIndex = 9;
labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
labelModifiedObject.MouseDown += LabelObject_MouseDown;
//
// labelSimpleObject
//
labelSimpleObject.AllowDrop = true;
labelSimpleObject.BackColor = SystemColors.Info;
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.ForeColor = SystemColors.ControlText;
labelSimpleObject.Location = new Point(264, 25);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(150, 70);
labelSimpleObject.TabIndex = 7;
labelSimpleObject.Text = "Простой";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
labelSimpleObject.MouseDown += LabelObject_MouseDown;
//
// GroupColor
//
GroupColor.Controls.Add(panelPurple);
GroupColor.Controls.Add(panelYellow);
GroupColor.Controls.Add(panelBlack);
GroupColor.Controls.Add(panelBlue);
GroupColor.Controls.Add(panelGray);
GroupColor.Controls.Add(panelGreen);
GroupColor.Controls.Add(panelWhite);
GroupColor.Controls.Add(panelRed);
GroupColor.ForeColor = SystemColors.ControlLightLight;
GroupColor.Location = new Point(6, 204);
GroupColor.Name = "GroupColor";
GroupColor.Size = new Size(345, 175);
GroupColor.TabIndex = 6;
GroupColor.TabStop = false;
GroupColor.Text = "Цвета";
//
// panelPurple
//
panelPurple.BackColor = Color.Purple;
panelPurple.Location = new Point(258, 102);
panelPurple.Name = "panelPurple";
panelPurple.Size = new Size(78, 55);
panelPurple.TabIndex = 3;
panelPurple.MouseDown += PanelColor_MouseDown;
//
// panelYellow
//
panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(258, 32);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(78, 55);
panelYellow.TabIndex = 1;
panelYellow.MouseDown += PanelColor_MouseDown;
//
// panelBlack
//
panelBlack.BackColor = Color.Black;
panelBlack.Location = new Point(174, 102);
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(78, 55);
panelBlack.TabIndex = 4;
panelBlack.MouseDown += PanelColor_MouseDown;
//
// panelBlue
//
panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(174, 32);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(78, 55);
panelBlue.TabIndex = 1;
panelBlue.MouseDown += PanelColor_MouseDown;
//
// panelGray
//
panelGray.BackColor = Color.Gray;
panelGray.Location = new Point(90, 102);
panelGray.Name = "panelGray";
panelGray.Size = new Size(78, 55);
panelGray.TabIndex = 5;
panelGray.MouseDown += PanelColor_MouseDown;
//
// panelGreen
//
panelGreen.BackColor = Color.Lime;
panelGreen.Location = new Point(90, 32);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(78, 55);
panelGreen.TabIndex = 1;
panelGreen.MouseDown += PanelColor_MouseDown;
//
// panelWhite
//
panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(6, 102);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(78, 55);
panelWhite.TabIndex = 2;
panelWhite.MouseDown += PanelColor_MouseDown;
//
// panelRed
//
panelRed.BackColor = Color.Red;
panelRed.Location = new Point(6, 32);
panelRed.Name = "panelRed";
panelRed.Size = new Size(78, 55);
panelRed.TabIndex = 0;
panelRed.MouseDown += PanelColor_MouseDown;
//
// checkBoxSecondCabin
//
checkBoxSecondCabin.AutoSize = true;
checkBoxSecondCabin.ForeColor = SystemColors.ControlLightLight;
checkBoxSecondCabin.Location = new Point(20, 172);
checkBoxSecondCabin.Name = "checkBoxSecondCabin";
checkBoxSecondCabin.Size = new Size(134, 24);
checkBoxSecondCabin.TabIndex = 5;
checkBoxSecondCabin.Text = "Вторая кабина";
checkBoxSecondCabin.UseVisualStyleBackColor = true;
//
// checkBoxReil
//
checkBoxReil.AutoSize = true;
checkBoxReil.ForeColor = SystemColors.ControlLightLight;
checkBoxReil.Location = new Point(20, 142);
checkBoxReil.Name = "checkBoxReil";
checkBoxReil.Size = new Size(78, 24);
checkBoxReil.TabIndex = 4;
checkBoxReil.Text = "Рельса";
checkBoxReil.UseVisualStyleBackColor = true;
//
// label2
//
label2.AutoSize = true;
label2.ForeColor = SystemColors.ControlLightLight;
label2.Location = new Point(6, 93);
label2.Name = "label2";
label2.Size = new Size(36, 20);
label2.TabIndex = 3;
label2.Text = "Вес:";
//
// label1
//
label1.AutoSize = true;
label1.ForeColor = SystemColors.ControlLightLight;
label1.Location = new Point(6, 50);
label1.Name = "label1";
label1.Size = new Size(76, 20);
label1.TabIndex = 2;
label1.Text = "Скорость:";
//
// numericUpDownWeight
//
numericUpDownWeight.BackColor = SystemColors.Info;
numericUpDownWeight.Location = new Point(100, 91);
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(150, 27);
numericUpDownWeight.TabIndex = 1;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// numericUpDownSpeed
//
numericUpDownSpeed.BackColor = SystemColors.Info;
numericUpDownSpeed.Location = new Point(100, 48);
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(150, 27);
numericUpDownSpeed.TabIndex = 0;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(6, 9);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(1017, 517);
pictureBoxObject.TabIndex = 1;
pictureBoxObject.TabStop = false;
//
// label4
//
label4.AutoSize = true;
label4.Location = new Point(513, 371);
label4.Name = "label4";
label4.Size = new Size(0, 20);
label4.TabIndex = 2;
//
// PanelObject
//
PanelObject.AllowDrop = true;
PanelObject.Controls.Add(pictureBoxObject);
PanelObject.Location = new Point(439, 12);
PanelObject.Name = "PanelObject";
PanelObject.Size = new Size(1032, 540);
PanelObject.TabIndex = 15;
PanelObject.DragDrop += PanelObject_DragDrop;
PanelObject.DragEnter += PanelObject_DragEnter;
//
// FormMonorailConfig
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
BackColor = SystemColors.ControlDarkDark;
ClientSize = new Size(1478, 559);
Controls.Add(PanelObject);
Controls.Add(label4);
Controls.Add(groupBox1);
Name = "FormMonorailConfig";
Text = "FormMonorailConfig";
groupBox1.ResumeLayout(false);
groupBox1.PerformLayout();
GroupColor.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).EndInit();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).EndInit();
PanelObject.ResumeLayout(false);
ResumeLayout(false);
PerformLayout();
}
#endregion
private GroupBox groupBox1;
private Label label2;
private Label label1;
private NumericUpDown numericUpDownWeight;
private NumericUpDown numericUpDownSpeed;
private GroupBox GroupColor;
private Panel panelYellow;
private Panel panelBlue;
private Panel panelGreen;
private Panel panelRed;
private CheckBox checkBoxSecondCabin;
private CheckBox checkBoxReil;
private Label labelModifiedObject;
private Label labelSimpleObject;
private Panel panelPurple;
private Panel panelBlack;
private Panel panelGray;
private Panel panelWhite;
private PictureBox pictureBoxObject;
private Label label4;
private Button ButtonOk;
private Button ButtonCancel;
private Panel PanelObject;
private Label label_body_color;
private Label label_additional_color;
}
}

View File

@ -0,0 +1,129 @@
using Monorail.DrawningObjects;
using Monorail.Entities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Monorail
{
public partial class FormMonorailConfig : Form
{
DrawningMonorail? _monorail = null;
public event Action<DrawningMonorail>? EventAddMonorail;
public FormMonorailConfig()
{
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, e) => Close();
}
private void DrawMonorail()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_monorail?.SetPosition(pictureBoxObject.Width / 3, pictureBoxObject.Height / 3);
_monorail?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
private void LabelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label)?.DoDragDrop((sender as Label)?.Name,
DragDropEffects.Move | DragDropEffects.Copy);
}
private void PanelColor_MouseDown(object sender, MouseEventArgs e)
{
(sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor,
DragDropEffects.Copy | DragDropEffects.Move);
}
private void PanelObject_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(DataFormats.Text) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void PanelObject_DragDrop(object sender, DragEventArgs e)
{
switch (e.Data?.GetData(DataFormats.Text).ToString())
{
case "labelSimpleObject":
_monorail = new DrawningMonorail((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, pictureBoxObject.Width,
pictureBoxObject.Height);
break;
case "labelModifiedObject":
_monorail = new DrawningSecondMonorail((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, Color.Black, checkBoxReil.Checked,
checkBoxSecondCabin.Checked, pictureBoxObject.Width,
pictureBoxObject.Height);
break;
}
DrawMonorail();
}
private void PanelColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(typeof(Color)) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void PanelColor_DragDrop(object sender, DragEventArgs e)
{
if (_monorail == null)
{
return;
}
switch (((Label)sender).Name)
{
case "label_body_color":
_monorail?.EntityMonorail?.setBodyColor((Color)e.Data.GetData(typeof(Color)));
break;
case "label_additional_color":
if (!(_monorail is DrawningSecondMonorail))
{
return;
}
(_monorail.EntityMonorail as EntitySecondMonorail)?
.setAdditionalColor(color: (Color)e.Data.GetData(typeof(Color)));
break;
}
DrawMonorail();
}
public void AddEvent(Action<DrawningMonorail> ev)
{
if (EventAddMonorail == null)
{
EventAddMonorail = ev;
}
else
{
EventAddMonorail += ev;
}
}
private void ButtonOk_Click(object sender, EventArgs e)
{
EventAddMonorail?.Invoke(_monorail);
Close();
}
}
}

View 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>

View File

@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Monorail.DrawningObjects;
using Monorail.Entities;
using System.Diagnostics.CodeAnalysis;
namespace Monorail.Generics
{
internal class DrawningMonorailEqutables : IEqualityComparer<DrawningMonorail?>
{
public bool Equals(DrawningMonorail? x, DrawningMonorail? y)
{
if(x==null || x.EntityMonorail == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityMonorail == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityMonorail.Speed != y.EntityMonorail.Speed)
{
return false;
}
if (x.EntityMonorail.Weight != y.EntityMonorail.Weight)
{
return false;
}
if (x.EntityMonorail.BodyColor != y.EntityMonorail.BodyColor)
{
return false;
}
if (x is DrawningSecondMonorail && y is DrawningSecondMonorail)
{
// TODO
EntitySecondMonorail entityX = (EntitySecondMonorail)x.EntityMonorail;
EntitySecondMonorail entityY = (EntitySecondMonorail)y.EntityMonorail;
if(entityX.AdditionalColor != entityY.AdditionalColor)
{
return false;
}
if(entityX.Monorails != entityY.Monorails)
{
return false;
}
if(entityX.SecondCabin != entityY.SecondCabin)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningMonorail obj)
{
return obj.GetHashCode();
}
}
}

View File

@ -0,0 +1,52 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Monorail.DrawningObjects;
using Monorail.Entities;
namespace Monorail.Generics
{
internal class MonorailCompareByColor : IComparer<DrawningMonorail?>
{
public int Compare(DrawningMonorail? x, DrawningMonorail? y)
{
if (x == null || x.EntityMonorail == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityMonorail == null)
{
throw new ArgumentNullException(nameof(y));
}
if(x.EntityMonorail.BodyColor.Name != y.EntityMonorail.BodyColor.Name)
{
return x.EntityMonorail.BodyColor.Name.CompareTo(y.EntityMonorail.BodyColor.Name);
}
if (x.GetType().Name != y.GetType().Name)
{
if (x is DrawningMonorail)
return -1;
else
return 1;
}
if (x.GetType().Name == y.GetType().Name && x is DrawningSecondMonorail)
{
EntitySecondMonorail entityX = (EntitySecondMonorail)x.EntityMonorail;
EntitySecondMonorail entityY = (EntitySecondMonorail)y.EntityMonorail;
if (entityX.AdditionalColor.Name != entityY.AdditionalColor.Name)
{
return entityX.AdditionalColor.Name.CompareTo(entityY.AdditionalColor.Name);
}
}
var speedCompare =
x.EntityMonorail.Speed.CompareTo(y.EntityMonorail.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityMonorail.Weight.CompareTo(y.EntityMonorail.Weight);
}
}
}

View File

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Monorail.DrawningObjects;
namespace Monorail.Generics
{
internal class MonorailCompareByType : IComparer<DrawningMonorail?>
{
public int Compare(DrawningMonorail? x, DrawningMonorail? y)
{
if(x == null || x.EntityMonorail == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityMonorail == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare =
x.EntityMonorail.Speed.CompareTo(y.EntityMonorail.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityMonorail.Weight.CompareTo(y.EntityMonorail.Weight);
}
}
}

View File

@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Monorail.Generics
{
internal class MonorailsCollectionInfo : IEquatable<MonorailsCollectionInfo>
{
public string Name { get; private set; }
public string Description { get; private set; }
public MonorailsCollectionInfo(string name, string description)
{
Name = name;
Description = description;
}
public bool Equals(MonorailsCollectionInfo? other)
{
return Name == other?.Name;
throw new NotImplementedException();
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}
}

View File

@ -0,0 +1,104 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Monorail.DrawningObjects;
using Monorail.MovementStrategy;
namespace Monorail.Generics
{
internal class MonorailsGenericCollection<T, U>
where T: DrawningMonorail
where U : IMoveableObject
{
public IEnumerable<T?> GetMonorails => _collection.GetMonorails();
private readonly int _pictureWidth;
private readonly int _pictureHeight;
private readonly int _placeSizeWidth = 295;
private readonly int _placeSizeHeight = 65;
private readonly SetGeneric<T> _collection;
public void Sort(IComparer<T?> comparer) =>
_collection.SortSet(comparer);
public MonorailsGenericCollection(int picWidth, int picHeight)
{
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = new SetGeneric<T>(width * height);
}
public static int operator +(MonorailsGenericCollection<T, U> collect, T obj)
{
if (obj == null)
{
return -1;
}
return collect?._collection.Insert(obj, new DrawningMonorailEqutables()) ?? -1;
}
public static T? operator -(MonorailsGenericCollection<T, U> collect, int pos)
{
T? obj = collect._collection[pos];
collect._collection.Remove(pos);
return obj;
}
public U? GetU(int pos)
{
return (U?)_collection[pos]?.GetMoveableObject;
}
public Bitmap ShowMonorails()
{
Bitmap bmp = new(_pictureWidth, _pictureHeight);
Graphics gr = Graphics.FromImage(bmp);
DrawBackground(gr);
DrawObjects(gr);
return bmp;
}
private void DrawBackground(Graphics g)
{
Pen pen = new(Color.Black, 3);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j)
{//линия рамзетки места
g.DrawLine(pen, i * _placeSizeWidth, j *
_placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth / 2 + 20, j *
_placeSizeHeight);
}
g.DrawLine(pen, i * _placeSizeWidth, 0, i *
_placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight);
}
}
private void DrawObjects(Graphics g)
{
int indexPlaces = 0;
int j = _pictureHeight / _placeSizeHeight - 1;
int ind = 0;
for (int i = 0; i < _collection.Count; i++)
{
// TODO получение объекта
DrawningMonorail? _monorail = _collection[indexPlaces];
indexPlaces++;
if (_monorail != null)
{
// TODO установка позиции
_monorail.SetPosition(ind * _placeSizeWidth, j * _placeSizeHeight);
// TODO прорисовка объекта
_monorail.DrawTransport(g);
}
if(ind == _pictureWidth / _placeSizeWidth - 1)
{
ind = 0;
j--;
}
else
{
ind++;
}
}
}
}
}

View File

@ -0,0 +1,137 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Monorail.DrawningObjects;
using Monorail.MovementStrategy;
namespace Monorail.Generics
{
internal class MonorailsGenericStorage
{
private static readonly char _separatorForKeyValue = '|';
private readonly char _separatorRecords = ';';
private static readonly char _separatorForObject = ':';
readonly Dictionary<MonorailsCollectionInfo, MonorailsGenericCollection<DrawningMonorail,
DrawningObjectMonorail>> _monorailsStorages;
public List<MonorailsCollectionInfo> Keys => _monorailsStorages.Keys.ToList();
private readonly int _pictureWidth;
private readonly int _pictureHeight;
public MonorailsGenericStorage(int pictureWidth, int pictureHeight)
{
_monorailsStorages = new Dictionary<MonorailsCollectionInfo, MonorailsGenericCollection<DrawningMonorail,
DrawningObjectMonorail>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight; ;
}
public void AddSet(string name)
{
//TO DO
if(_monorailsStorages.ContainsKey(new MonorailsCollectionInfo(name, string.Empty)))
{
MessageBox.Show("Словарь уже имеет объект с таким названием", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_monorailsStorages.Add(new MonorailsCollectionInfo(name, string.Empty),
new MonorailsGenericCollection<DrawningMonorail,
DrawningObjectMonorail>(_pictureWidth, _pictureHeight));
}
public void DelSet(string name)
{
if (_monorailsStorages[new MonorailsCollectionInfo(name, string.Empty)] == null)
{
return;
}
_monorailsStorages.Remove(new MonorailsCollectionInfo(name, string.Empty));
}
public MonorailsGenericCollection<DrawningMonorail, DrawningObjectMonorail> this[string ind]
{
get
{
MonorailsCollectionInfo index = new MonorailsCollectionInfo(ind, string.Empty);
if (_monorailsStorages.ContainsKey(index))
{
return _monorailsStorages[index];
}
return null;
}
}
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<MonorailsCollectionInfo,MonorailsGenericCollection<DrawningMonorail, DrawningObjectMonorail>>
record in _monorailsStorages)
{
StringBuilder records = new();
foreach (DrawningMonorail? elem in record.Value.GetMonorails)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key.Name}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
throw new Exception("Невалидная операция, нет данных для сохранения");
}
using StreamWriter sw = new(filename);
sw.Write($"MonorailStorage{Environment.NewLine}{data}");
return;
}
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new Exception("Файл не найден");
}
using (StreamReader sr = File.OpenText(filename))
{
string str = sr.ReadLine();
if (str == null || str.Length == 0)
{
throw new Exception("Нет данных для загрузки");
}
if (!str.StartsWith("MonorailStorage"))
{
throw new Exception("Неверный формат данных");
}
_monorailsStorages.Clear();
string strs = "";
while ((strs = sr.ReadLine()) != null)
{
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
continue;
}
MonorailsGenericCollection<DrawningMonorail, DrawningObjectMonorail> collection =
new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawningMonorail? monorail = elem?.CreateDrawningMonorail(_separatorForObject,
_pictureWidth, _pictureHeight);
if (monorail != null)
{
if ((collection + monorail) == -1)
{
throw new Exception("Ошибка добавления в коллекцию");
}
}
}
_monorailsStorages.Add(new MonorailsCollectionInfo(record[0], string.Empty), collection);
}
}
}
}
}

View File

@ -0,0 +1,105 @@
using Monorail.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
namespace Monorail.Generics
{
internal class SetGeneric<T>
where T : class
{
private readonly List<T?> _places;
public int Count => _places.Count;
private readonly int _maxCount;
public SetGeneric(int count)
{
_maxCount = count;
_places = new List<T?>(count);
}
public void SortSet(IComparer<T?> comparer) =>
_places.Sort(comparer);
public int Insert(T monorail, IEqualityComparer<T?>? equal = null)
{
if (_places.Count == _maxCount)
throw new StorageOverflowException(_maxCount);
Insert(monorail, 0, equal);
return 0;
}
public bool Insert(T monorail, int position, IEqualityComparer<T?>? equal = null)
{
if (Count == _maxCount || position >= _maxCount)
throw new StorageOverflowException(Count);
if (position < 0 || monorail == null)
throw new StorageOverflowException("Ошибка. Объект не найден или введённый " +
"номер позиции = отрицательное число");
if (equal != null)
{
if (_places.Contains(monorail, equal))
throw new ArgumentException(nameof(monorail));
}
_places.Insert(position, monorail);
return true;
}
public bool Remove(int position)
{
// TODO проверка позиции
if (position >= Count)
{
throw new MonorailNotFoundException(position);
}
// TODO удаление объекта из массива, присвоив элементу массива значение null
if (_places[position] != null)
{
_places[position] = null;
return true;
}
else
{
throw new MonorailNotFoundException(position);
}
}
public T? this[int position]
{
get {
// TODO проверка позиции
if (position >= Count)
{
return null;
}
return _places[position];
}
set
{
if(position >= Count)
{
return;
}
if (_places[position] != null)
{
return;
}
else
{
_places[position] = this[position];
}
}
}
public IEnumerable<T?> GetMonorails(int? maxMonorails = null)
{
for (int i = 0; i < _places.Count; ++i)
{
yield return _places[i];
if (maxMonorails.HasValue && i == maxMonorails.Value)
{
yield break;
}
}
}
}
}

View File

@ -8,4 +8,14 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.AppSettings" Version="2.2.2" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Xml" Version="1.1.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,72 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Monorail.MovementStrategy
{
public abstract class AbstractStrategy
{
private IMoveableObject? _moveableObject;
private Status _state = Status.NotInit;
protected int FieldWidth { get; private set; }
protected int FieldHeight { get; private set; }
public Status GetStatus() { return _state; }
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;
}
public void MakeStep()
{
if (_state != Status.InProgress)
{
return;
}
if (IsTargetDestinaion())
{
_state = Status.Finish;
return;
}
MoveToTarget();
}
protected bool MoveLeft() => MoveTo(DirectionType.Left);
protected bool MoveRight() => MoveTo(DirectionType.Right);
protected bool MoveUp() => MoveTo(DirectionType.Up);
protected bool MoveDown() => MoveTo(DirectionType.Down);
protected ObjectParameters? GetObjectParameters =>
_moveableObject?.GetObjectPosition;
protected int? GetStep()
{
if (_state != Status.InProgress)
{
return null;
}
return _moveableObject?.GetStep;
}
protected abstract void MoveToTarget();
protected abstract bool IsTargetDestinaion();
private bool MoveTo(DirectionType directionType)
{
if (_state != Status.InProgress)
{
return false;
}
if (_moveableObject?.CheckCanMove(directionType) ?? false)
{
_moveableObject.MoveObject(directionType);
return true;
}
return false;
}
}
}

View File

@ -0,0 +1,36 @@
using Monorail.DrawningObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Monorail.MovementStrategy
{
public class DrawningObjectMonorail :IMoveableObject
{
private readonly DrawningMonorail? _drawningMonorail = null;
public DrawningObjectMonorail(DrawningMonorail drawningMonorail)
{
_drawningMonorail = drawningMonorail;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_drawningMonorail == null || _drawningMonorail.EntityMonorail ==
null)
{
return null;
}
return new ObjectParameters(_drawningMonorail.GetPosX,
_drawningMonorail.GetPosY, _drawningMonorail.GetWidth, _drawningMonorail.GetHeight);
}
}
public int GetStep => (int)(_drawningMonorail?.EntityMonorail?.Step ?? 0);
public bool CheckCanMove(DirectionType direction) =>
_drawningMonorail?.CanMove(direction) ?? false;
public void MoveObject(DirectionType direction) =>
_drawningMonorail?.MoveTransport(direction);
}
}

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Monorail.MovementStrategy
{
public interface IMoveableObject
{
ObjectParameters? GetObjectPosition { get; }
int GetStep { get; }
bool CheckCanMove(DirectionType direction);
void MoveObject(DirectionType direction);
}
}

View File

@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Monorail.MovementStrategy
{
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();
}
}
}
}
}

View File

@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Monorail.MovementStrategy
{
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();
}
}
}
}
}

View File

@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Monorail.MovementStrategy
{
public class ObjectParameters
{
private readonly int _x;
private readonly int _y;
private readonly int _width;
private readonly int _height;
public int LeftBorder => _x;
public int TopBorder => _y;
public int RightBorder => _x + _width;
public int DownBorder => _y + _height;
public int ObjectMiddleHorizontal => _x + _width / 2;
public int ObjectMiddleVertical => _y + _height / 2;
public ObjectParameters(int x, int y, int width, int height)
{
_x = x;
_y = y;
_width = width;
_height = height;
}
}
}

View File

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

View File

@ -1,3 +1,12 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Extensions.Logging;
using System.Configuration;
using Serilog.Settings.AppSettings;
using Serilog.Settings.Xml;
using Serilog.Sinks.File;
namespace Monorail
{
internal static class Program
@ -11,7 +20,30 @@ namespace Monorail
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
string logFolderPath = Path.Combine(AppContext.BaseDirectory, "Logs");
string logFilePath = Path.Combine(logFolderPath, "monoraillog-{Date}.log");
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.File(logFilePath, rollingInterval: RollingInterval.Day)
.CreateLogger();
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormMonorailCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormMonorailCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(Log.Logger);
});
}
}
}

View File

@ -0,0 +1,103 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Monorail.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("Monorail.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Перезаписывает свойство CurrentUICulture текущего потока для всех
/// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap down_arrow {
get {
object obj = ResourceManager.GetObject("down-arrow", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap left_arrow {
get {
object obj = ResourceManager.GetObject("left-arrow", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap right_arrow {
get {
object obj = ResourceManager.GetObject("right-arrow", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap upper_arrow {
get {
object obj = ResourceManager.GetObject("upper-arrow", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 281 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 265 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 224 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 264 B