23 Commits

Author SHA1 Message Date
ef7754bdf9 Лаб8 сдана 2022-11-22 16:15:15 +04:00
155ebec8ff баг фикс 1 2022-11-21 20:29:49 +04:00
a7027333d8 IEquatable AbstractMap 2022-11-21 19:43:07 +04:00
5a1cdcd4b2 Сортировка 2022-11-21 19:27:25 +04:00
38def0fbc5 Сравнение объектов 2022-11-21 17:38:47 +04:00
88b702d5b5 Почищен код 1 2022-11-21 17:06:04 +04:00
3f65961713 Сдана лаб7, требуется чистка кода 2022-11-08 16:15:06 +04:00
47dfc705d8 Добавлен логгер, осталось почистить код и убедиться в работоспособности 2022-11-08 15:01:50 +04:00
7009f2b1b7 Добавлены исключения и их обработка, немного изменена отрисовка объектов в хранилище и логика их хранения 2022-11-08 15:00:29 +04:00
7f15f74c84 Исправлены ошибки 2022-11-08 14:56:42 +04:00
630de13d2c Требования выполнены, лабораторная 6 готова 2022-11-04 19:32:14 +04:00
75671e0272 Основной функционал готов. Осталось переделать под требования. 2022-11-04 19:14:59 +04:00
11c83fd8b0 Добавлены методы записи, сохранения и загрузки данных в MapsCollection 2022-11-04 19:00:29 +04:00
dded2fe5dc Добавлены методы в MapWithSetLocomotivesGeneric 2022-11-04 18:46:34 +04:00
6f35bd337b Изменение интерфейса IDrawningObject и его реализации DrawningObjectLocomotive 2022-11-04 18:37:11 +04:00
032bf5d2a2 Создан класс ExtentionLocomotive, решена проблема с именами цветов в FormLocomotiveConfig 2022-11-04 18:29:36 +04:00
75190e8594 Правки. Сданная Лабораторная №5 2022-10-25 15:44:49 +04:00
6b7a6625db Базовая логика готова. Необходимо почистить код и свериться с требованиями. 2022-10-23 17:02:32 +04:00
58fce94948 Add config form 2022-10-23 15:36:01 +04:00
f4a5cc3dd2 Перевод интерфейса на английский в соответствии с требованием 2022-10-14 17:32:23 +04:00
f755c40397 Этап 3. Обновление формы 2022-10-10 19:03:51 +04:00
a9d7e440cc Этап 2. Добавлен класс MapsCollection 2022-10-10 18:26:35 +04:00
40da0fe01d Этап 1. Переход с массива на список. 2022-10-10 17:33:07 +04:00
24 changed files with 1501 additions and 132 deletions

View File

@@ -6,7 +6,7 @@ using System.Threading.Tasks;
namespace Locomotive
{
internal abstract class AbstractMap
internal abstract class AbstractMap : IEquatable<AbstractMap>
{
private IDrawningObject _drawningObject = null;
protected int[,] _map = null;
@@ -164,5 +164,29 @@ namespace Locomotive
protected abstract void DrawRoadPart(Graphics g, int i, int j);
protected abstract void DrawBarrierPart(Graphics g, int i, int j);
public bool Equals(AbstractMap? other)
{
if (other == null)
{
return false;
}
if (other == null)
{
return false;
}
if (_width != other._width) return false;
if (_height != other._height) return false;
if (_size_x != other._size_x) return false;
if (_size_y != other._size_y) return false;
for (int i = 0; i < _map.GetLength(0); i++)
{
for (int j = 0; j < _map.GetLength(1); j++)
{
if (_map[i,j] != other._map[i,j]) return false;
}
}
return true;
}
}
}

View File

@@ -38,6 +38,20 @@ namespace Locomotive
_locomotiveHeight = locomotiveHeight;
}
public void SetBaseColor(Color color)
{
if (Locomotive is EntityWarmlyLocomotive)
{
Locomotive = (EntityWarmlyLocomotive)Locomotive;
if (Locomotive is not null)
{
Locomotive = new EntityWarmlyLocomotive(Locomotive.Speed, Locomotive.Weight, color, (Locomotive as EntityWarmlyLocomotive).ExtraColor, (Locomotive as EntityWarmlyLocomotive).Pipe, (Locomotive as EntityWarmlyLocomotive).FuelStorage);
return;
}
}
Locomotive = new EntityLocomotive(Locomotive.Speed, Locomotive.Weight, color);
}
/// Установка позиции локомотива
public void SetPosition(int x, int y, int width, int height)
{

View File

@@ -17,6 +17,8 @@ namespace Locomotive
public float Step => _locomotive?.Locomotive?.Step ?? 0;
public DrawningLocomotive GetLocomotive => _locomotive;
public void DrawningObject(Graphics g)
{
_locomotive?.DrawTransport(g);
@@ -26,7 +28,6 @@ namespace Locomotive
{
return _locomotive?.GetCurrentPosition() ?? default;
}
public void MoveObject(Direction direction)
{
_locomotive?.MoveTransport(direction);
@@ -37,5 +38,47 @@ namespace Locomotive
_locomotive?.SetPosition(x, y, width, height);
}
public string getInfo() => _locomotive?.getDataForSave();
public static IDrawningObject Create(string data) => new DrawningObjectLocomotive(data.createDrawningLocomotive());
public bool Equals(IDrawningObject? other)
{
if (other == null)
{
return false;
}
var otherLocomotive = other as DrawningObjectLocomotive;
if (otherLocomotive == null)
{
return false;
}
var locomotive = _locomotive.Locomotive;
var otherLocomotiveLocomotive = otherLocomotive._locomotive.Locomotive;
if (locomotive.GetType().Name != otherLocomotiveLocomotive.GetType().Name) return false;
if (locomotive.Speed != otherLocomotiveLocomotive.Speed)
{
return false;
}
if (locomotive.Weight != otherLocomotiveLocomotive.Weight)
{
return false;
}
if (locomotive.BodyColor != otherLocomotiveLocomotive.BodyColor)
{
return false;
}
// проверка в случае продвинутого объекта
if (locomotive is EntityWarmlyLocomotive entityWarmlyLocomotive && otherLocomotiveLocomotive is EntityWarmlyLocomotive otherEntityWarmlyLocomotive)
{
if (entityWarmlyLocomotive.ExtraColor != otherEntityWarmlyLocomotive.ExtraColor) return false;
if (entityWarmlyLocomotive.Pipe != otherEntityWarmlyLocomotive.Pipe) return false;
if (entityWarmlyLocomotive.FuelStorage != otherEntityWarmlyLocomotive.FuelStorage) return false;
}
return true;
}
}
}

View File

@@ -14,6 +14,15 @@ namespace Locomotive
Locomotive = new EntityWarmlyLocomotive(speed, weight, bodyColor, extraColor, pipe, storage);
}
public void SetExtraColor(Color color)
{
Locomotive = Locomotive as EntityWarmlyLocomotive;
if (Locomotive is not null)
{
Locomotive = new EntityWarmlyLocomotive(Locomotive.Speed, Locomotive.Weight, Locomotive.BodyColor, color, (Locomotive as EntityWarmlyLocomotive).Pipe, (Locomotive as EntityWarmlyLocomotive).FuelStorage);
}
}
public override void DrawTransport(Graphics g)
{
if (Locomotive is not EntityWarmlyLocomotive warmlyLocomotive)

View File

@@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Locomotive
{
internal static class ExtentionLocomotive
{
private static readonly char _separatorForObject = ':';
public static string getDataForSave(this DrawningLocomotive drawningLocomotive)
{
var locomotive = drawningLocomotive.Locomotive;
var str = $"{locomotive.Speed}{_separatorForObject}{locomotive.Weight}{_separatorForObject}{locomotive.BodyColor.Name}";
if (locomotive is not EntityWarmlyLocomotive warmlyLocomotive)
{
return str;
}
return $"{str}{_separatorForObject}{warmlyLocomotive.ExtraColor.Name}{_separatorForObject}{warmlyLocomotive.Pipe}{_separatorForObject}{warmlyLocomotive.FuelStorage}";
}
public static DrawningLocomotive createDrawningLocomotive(this string info)
{
string[] strs = info.Split(_separatorForObject);
if (strs.Length == 3)
{
return new DrawningLocomotive(
Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]),
Color.FromName(strs[2])
);
}
if (strs.Length == 6)
{
return new DrawningWarmlyLocomotive(
Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]),
Color.FromName(strs[2]),
Color.FromName(strs[3]),
Convert.ToBoolean(strs[4]),
Convert.ToBoolean(strs[5])
);
}
return null;
}
}
}

View File

@@ -3,7 +3,6 @@ namespace Locomotive
public partial class FormLocomotive : Form
{
private DrawningLocomotive _locomotive;
public DrawningLocomotive SelectedLocomotive { get; private set; }
public FormLocomotive()
@@ -41,7 +40,6 @@ namespace Locomotive
SetData();
Draw();
}
private void ButtonMove_Click(object sender, EventArgs e)
{
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>

View File

@@ -0,0 +1,371 @@
namespace Locomotive
{
partial class FormLocomotiveConfig
{
/// <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.groupBoxConfig = new System.Windows.Forms.GroupBox();
this.labelModifiedObject = new System.Windows.Forms.Label();
this.labelSimpleObject = new System.Windows.Forms.Label();
this.groupBoxColors = new System.Windows.Forms.GroupBox();
this.panelPurple = new System.Windows.Forms.Panel();
this.panelBlack = new System.Windows.Forms.Panel();
this.panelGray = new System.Windows.Forms.Panel();
this.panelWhite = new System.Windows.Forms.Panel();
this.panelYellow = new System.Windows.Forms.Panel();
this.panelGreen = new System.Windows.Forms.Panel();
this.panelBlue = new System.Windows.Forms.Panel();
this.panelRed = new System.Windows.Forms.Panel();
this.checkBoxFuelStorage = new System.Windows.Forms.CheckBox();
this.checkBoxPipe = new System.Windows.Forms.CheckBox();
this.numericUpDownWeight = new System.Windows.Forms.NumericUpDown();
this.labelWeight = new System.Windows.Forms.Label();
this.numericUpDownSpeed = new System.Windows.Forms.NumericUpDown();
this.labelSpeed = new System.Windows.Forms.Label();
this.panelObject = new System.Windows.Forms.Panel();
this.labelDopColor = new System.Windows.Forms.Label();
this.labelBaseColor = new System.Windows.Forms.Label();
this.pictureBoxObject = new System.Windows.Forms.PictureBox();
this.buttonAdd = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.groupBoxConfig.SuspendLayout();
this.groupBoxColors.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).BeginInit();
this.panelObject.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).BeginInit();
this.SuspendLayout();
//
// groupBoxConfig
//
this.groupBoxConfig.Controls.Add(this.labelModifiedObject);
this.groupBoxConfig.Controls.Add(this.labelSimpleObject);
this.groupBoxConfig.Controls.Add(this.groupBoxColors);
this.groupBoxConfig.Controls.Add(this.checkBoxFuelStorage);
this.groupBoxConfig.Controls.Add(this.checkBoxPipe);
this.groupBoxConfig.Controls.Add(this.numericUpDownWeight);
this.groupBoxConfig.Controls.Add(this.labelWeight);
this.groupBoxConfig.Controls.Add(this.numericUpDownSpeed);
this.groupBoxConfig.Controls.Add(this.labelSpeed);
this.groupBoxConfig.Location = new System.Drawing.Point(12, 12);
this.groupBoxConfig.Name = "groupBoxConfig";
this.groupBoxConfig.Size = new System.Drawing.Size(453, 260);
this.groupBoxConfig.TabIndex = 0;
this.groupBoxConfig.TabStop = false;
this.groupBoxConfig.Text = "Configuration";
//
// labelModifiedObject
//
this.labelModifiedObject.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelModifiedObject.Location = new System.Drawing.Point(312, 200);
this.labelModifiedObject.Name = "labelModifiedObject";
this.labelModifiedObject.Size = new System.Drawing.Size(115, 45);
this.labelModifiedObject.TabIndex = 8;
this.labelModifiedObject.Text = "Modified";
this.labelModifiedObject.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelModifiedObject.MouseDown += new System.Windows.Forms.MouseEventHandler(this.labelObject_MouseDown);
//
// labelSimpleObject
//
this.labelSimpleObject.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelSimpleObject.Location = new System.Drawing.Point(179, 200);
this.labelSimpleObject.Name = "labelSimpleObject";
this.labelSimpleObject.Size = new System.Drawing.Size(115, 45);
this.labelSimpleObject.TabIndex = 7;
this.labelSimpleObject.Text = "Simple";
this.labelSimpleObject.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelSimpleObject.MouseDown += new System.Windows.Forms.MouseEventHandler(this.labelObject_MouseDown);
//
// groupBoxColors
//
this.groupBoxColors.Controls.Add(this.panelPurple);
this.groupBoxColors.Controls.Add(this.panelBlack);
this.groupBoxColors.Controls.Add(this.panelGray);
this.groupBoxColors.Controls.Add(this.panelWhite);
this.groupBoxColors.Controls.Add(this.panelYellow);
this.groupBoxColors.Controls.Add(this.panelGreen);
this.groupBoxColors.Controls.Add(this.panelBlue);
this.groupBoxColors.Controls.Add(this.panelRed);
this.groupBoxColors.Location = new System.Drawing.Point(179, 26);
this.groupBoxColors.Name = "groupBoxColors";
this.groupBoxColors.Size = new System.Drawing.Size(248, 156);
this.groupBoxColors.TabIndex = 6;
this.groupBoxColors.TabStop = false;
this.groupBoxColors.Text = "Colors";
//
// panelPurple
//
this.panelPurple.BackColor = System.Drawing.Color.Fuchsia;
this.panelPurple.Location = new System.Drawing.Point(193, 102);
this.panelPurple.Name = "panelPurple";
this.panelPurple.Size = new System.Drawing.Size(43, 40);
this.panelPurple.TabIndex = 3;
//
// panelBlack
//
this.panelBlack.BackColor = System.Drawing.Color.Black;
this.panelBlack.Location = new System.Drawing.Point(132, 102);
this.panelBlack.Name = "panelBlack";
this.panelBlack.Size = new System.Drawing.Size(43, 40);
this.panelBlack.TabIndex = 2;
//
// panelGray
//
this.panelGray.BackColor = System.Drawing.Color.Gray;
this.panelGray.Location = new System.Drawing.Point(72, 102);
this.panelGray.Name = "panelGray";
this.panelGray.Size = new System.Drawing.Size(43, 40);
this.panelGray.TabIndex = 3;
//
// panelWhite
//
this.panelWhite.BackColor = System.Drawing.Color.White;
this.panelWhite.Location = new System.Drawing.Point(11, 102);
this.panelWhite.Name = "panelWhite";
this.panelWhite.Size = new System.Drawing.Size(43, 40);
this.panelWhite.TabIndex = 2;
//
// panelYellow
//
this.panelYellow.BackColor = System.Drawing.Color.Yellow;
this.panelYellow.Location = new System.Drawing.Point(193, 31);
this.panelYellow.Name = "panelYellow";
this.panelYellow.Size = new System.Drawing.Size(43, 40);
this.panelYellow.TabIndex = 1;
//
// panelGreen
//
this.panelGreen.BackColor = System.Drawing.Color.Green;
this.panelGreen.Location = new System.Drawing.Point(72, 31);
this.panelGreen.Name = "panelGreen";
this.panelGreen.Size = new System.Drawing.Size(43, 40);
this.panelGreen.TabIndex = 1;
//
// panelBlue
//
this.panelBlue.BackColor = System.Drawing.Color.Blue;
this.panelBlue.Location = new System.Drawing.Point(133, 31);
this.panelBlue.Name = "panelBlue";
this.panelBlue.Size = new System.Drawing.Size(43, 40);
this.panelBlue.TabIndex = 1;
//
// panelRed
//
this.panelRed.BackColor = System.Drawing.Color.Red;
this.panelRed.Location = new System.Drawing.Point(11, 31);
this.panelRed.Name = "panelRed";
this.panelRed.Size = new System.Drawing.Size(43, 40);
this.panelRed.TabIndex = 0;
//
// checkBoxFuelStorage
//
this.checkBoxFuelStorage.AutoSize = true;
this.checkBoxFuelStorage.Location = new System.Drawing.Point(7, 158);
this.checkBoxFuelStorage.Name = "checkBoxFuelStorage";
this.checkBoxFuelStorage.Size = new System.Drawing.Size(146, 24);
this.checkBoxFuelStorage.TabIndex = 5;
this.checkBoxFuelStorage.Text = "Add Fuel Storage";
this.checkBoxFuelStorage.UseVisualStyleBackColor = true;
//
// checkBoxPipe
//
this.checkBoxPipe.AutoSize = true;
this.checkBoxPipe.Location = new System.Drawing.Point(7, 128);
this.checkBoxPipe.Name = "checkBoxPipe";
this.checkBoxPipe.Size = new System.Drawing.Size(92, 24);
this.checkBoxPipe.TabIndex = 4;
this.checkBoxPipe.Text = "Add Pipe";
this.checkBoxPipe.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
this.numericUpDownWeight.Location = new System.Drawing.Point(75, 75);
this.numericUpDownWeight.Maximum = new decimal(new int[] {
500,
0,
0,
0});
this.numericUpDownWeight.Name = "numericUpDownWeight";
this.numericUpDownWeight.Size = new System.Drawing.Size(68, 27);
this.numericUpDownWeight.TabIndex = 3;
this.numericUpDownWeight.Value = new decimal(new int[] {
100,
0,
0,
0});
//
// labelWeight
//
this.labelWeight.AutoSize = true;
this.labelWeight.Location = new System.Drawing.Point(7, 77);
this.labelWeight.Name = "labelWeight";
this.labelWeight.Size = new System.Drawing.Size(63, 20);
this.labelWeight.TabIndex = 2;
this.labelWeight.Text = "Weight: ";
//
// numericUpDownSpeed
//
this.numericUpDownSpeed.Location = new System.Drawing.Point(74, 31);
this.numericUpDownSpeed.Maximum = new decimal(new int[] {
500,
0,
0,
0});
this.numericUpDownSpeed.Name = "numericUpDownSpeed";
this.numericUpDownSpeed.Size = new System.Drawing.Size(69, 27);
this.numericUpDownSpeed.TabIndex = 1;
this.numericUpDownSpeed.Value = new decimal(new int[] {
100,
0,
0,
0});
//
// labelSpeed
//
this.labelSpeed.AutoSize = true;
this.labelSpeed.Location = new System.Drawing.Point(6, 33);
this.labelSpeed.Name = "labelSpeed";
this.labelSpeed.Size = new System.Drawing.Size(62, 20);
this.labelSpeed.TabIndex = 0;
this.labelSpeed.Text = " Speed: ";
//
// panelObject
//
this.panelObject.AllowDrop = true;
this.panelObject.Controls.Add(this.labelDopColor);
this.panelObject.Controls.Add(this.labelBaseColor);
this.panelObject.Controls.Add(this.pictureBoxObject);
this.panelObject.Location = new System.Drawing.Point(471, 22);
this.panelObject.Name = "panelObject";
this.panelObject.Size = new System.Drawing.Size(419, 250);
this.panelObject.TabIndex = 1;
this.panelObject.DragDrop += new System.Windows.Forms.DragEventHandler(this.panelObject_DragDrop);
this.panelObject.DragEnter += new System.Windows.Forms.DragEventHandler(this.panelObject_DragEnter);
//
// labelDopColor
//
this.labelDopColor.AllowDrop = true;
this.labelDopColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelDopColor.Location = new System.Drawing.Point(232, 16);
this.labelDopColor.Name = "labelDopColor";
this.labelDopColor.Size = new System.Drawing.Size(115, 45);
this.labelDopColor.TabIndex = 9;
this.labelDopColor.Text = "Extra Color";
this.labelDopColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelDopColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.labelDopColor_DragDrop);
this.labelDopColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.labelDopColor_DragEnter);
//
// labelBaseColor
//
this.labelBaseColor.AllowDrop = true;
this.labelBaseColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelBaseColor.Location = new System.Drawing.Point(69, 16);
this.labelBaseColor.Name = "labelBaseColor";
this.labelBaseColor.Size = new System.Drawing.Size(115, 45);
this.labelBaseColor.TabIndex = 8;
this.labelBaseColor.Text = "Base Color";
this.labelBaseColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelBaseColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.labelBaseColor_DragDrop);
this.labelBaseColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.labelBaseColor_DragEnter);
//
// pictureBoxObject
//
this.pictureBoxObject.Location = new System.Drawing.Point(16, 67);
this.pictureBoxObject.Name = "pictureBoxObject";
this.pictureBoxObject.Size = new System.Drawing.Size(386, 168);
this.pictureBoxObject.TabIndex = 0;
this.pictureBoxObject.TabStop = false;
//
// buttonAdd
//
this.buttonAdd.Location = new System.Drawing.Point(487, 278);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(168, 29);
this.buttonAdd.TabIndex = 2;
this.buttonAdd.Text = "Add";
this.buttonAdd.UseVisualStyleBackColor = true;
this.buttonAdd.Click += new System.EventHandler(this.buttonAdd_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(703, 278);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(170, 29);
this.buttonCancel.TabIndex = 3;
this.buttonCancel.Text = "Cancel";
this.buttonCancel.UseVisualStyleBackColor = true;
//
// FormLocomotiveConfig
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(902, 315);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonAdd);
this.Controls.Add(this.panelObject);
this.Controls.Add(this.groupBoxConfig);
this.Name = "FormLocomotiveConfig";
this.Text = "Object Creation";
this.groupBoxConfig.ResumeLayout(false);
this.groupBoxConfig.PerformLayout();
this.groupBoxColors.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).EndInit();
this.panelObject.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).EndInit();
this.ResumeLayout(false);
}
#endregion
private GroupBox groupBoxConfig;
private NumericUpDown numericUpDownSpeed;
private Label labelSpeed;
private NumericUpDown numericUpDownWeight;
private Label labelWeight;
private CheckBox checkBoxFuelStorage;
private CheckBox checkBoxPipe;
private GroupBox groupBoxColors;
private Panel panelRed;
private Panel panelPurple;
private Panel panelBlack;
private Panel panelGray;
private Panel panelWhite;
private Panel panelYellow;
private Panel panelGreen;
private Panel panelBlue;
private Label labelSimpleObject;
private Label labelModifiedObject;
private Panel panelObject;
private PictureBox pictureBoxObject;
private Label labelDopColor;
private Label labelBaseColor;
private Button buttonAdd;
private Button buttonCancel;
}
}

View File

@@ -0,0 +1,141 @@
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 Locomotive
{
public partial class FormLocomotiveConfig : Form
{
DrawningLocomotive _locomotive = null;
private event Action<DrawningLocomotive> eventAddLocomotive;
public void AddEvent(Action<DrawningLocomotive> ev)
{
if (eventAddLocomotive == null)
{
eventAddLocomotive = new Action<DrawningLocomotive>(ev);
}
else
{
eventAddLocomotive += ev;
}
}
private void buttonAdd_Click(object sender, EventArgs e)
{
eventAddLocomotive?.Invoke(_locomotive);
Close();
}
public FormLocomotiveConfig()
{
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 += (object sender, EventArgs e) => Close();
}
private void labelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label).DoDragDrop((sender as Label).Name, DragDropEffects.Move | DragDropEffects.Copy);
}
private void panelObject_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text))
{
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":
_locomotive = new DrawningLocomotive((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value, Color.White);
break;
case "labelModifiedObject":
_locomotive = new DrawningWarmlyLocomotive((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value,
Color.White, Color.Black,
checkBoxPipe.Checked, checkBoxFuelStorage.Checked);
break;
}
DrawLocomotive();
}
private void PanelColor_MouseDown(object sender, MouseEventArgs e)
{
(sender as Control).DoDragDrop((sender as Control).BackColor, DragDropEffects.Move | DragDropEffects.Copy);
}
private void DrawLocomotive()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_locomotive?.SetPosition(5, 5, pictureBoxObject.Width, pictureBoxObject.Height);
_locomotive?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
private void labelBaseColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void labelBaseColor_DragDrop(object sender, DragEventArgs e)
{
_locomotive.SetBaseColor((Color)e.Data.GetData(typeof(Color)));
DrawLocomotive();
}
private void labelDopColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void labelDopColor_DragDrop(object sender, DragEventArgs e)
{
if (_locomotive is DrawningWarmlyLocomotive)
{
var locomotive = _locomotive as DrawningWarmlyLocomotive;
locomotive.SetExtraColor((Color)e.Data.GetData(typeof(Color)));
}
DrawLocomotive();
}
}
}

View File

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

View File

@@ -29,6 +29,13 @@
private void InitializeComponent()
{
this.groupBoxTools = new System.Windows.Forms.GroupBox();
this.ButtonSortByType = new System.Windows.Forms.Button();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.buttonDeleteMap = new System.Windows.Forms.Button();
this.listBoxMaps = new System.Windows.Forms.ListBox();
this.buttonAddMap = new System.Windows.Forms.Button();
this.textBoxNewMapName = new System.Windows.Forms.TextBox();
this.comboBoxSelectorMap = new System.Windows.Forms.ComboBox();
this.buttonLeft = new System.Windows.Forms.Button();
this.buttonRight = new System.Windows.Forms.Button();
this.buttonDown = new System.Windows.Forms.Button();
@@ -38,14 +45,25 @@
this.buttonRemoveLocomotive = new System.Windows.Forms.Button();
this.maskedTextBoxPosition = new System.Windows.Forms.MaskedTextBox();
this.buttonAddLocomotive = new System.Windows.Forms.Button();
this.comboBoxSelectorMap = new System.Windows.Forms.ComboBox();
this.pictureBox = new System.Windows.Forms.PictureBox();
this.menuStrip = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.loadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.loadFileDialog = new System.Windows.Forms.OpenFileDialog();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.ButtonSortByColor = new System.Windows.Forms.Button();
this.groupBoxTools.SuspendLayout();
this.groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
this.menuStrip.SuspendLayout();
this.SuspendLayout();
//
// groupBoxTools
//
this.groupBoxTools.Controls.Add(this.ButtonSortByColor);
this.groupBoxTools.Controls.Add(this.ButtonSortByType);
this.groupBoxTools.Controls.Add(this.groupBox1);
this.groupBoxTools.Controls.Add(this.buttonLeft);
this.groupBoxTools.Controls.Add(this.buttonRight);
this.groupBoxTools.Controls.Add(this.buttonDown);
@@ -55,20 +73,92 @@
this.groupBoxTools.Controls.Add(this.buttonRemoveLocomotive);
this.groupBoxTools.Controls.Add(this.maskedTextBoxPosition);
this.groupBoxTools.Controls.Add(this.buttonAddLocomotive);
this.groupBoxTools.Controls.Add(this.comboBoxSelectorMap);
this.groupBoxTools.Dock = System.Windows.Forms.DockStyle.Right;
this.groupBoxTools.Location = new System.Drawing.Point(580, 0);
this.groupBoxTools.Location = new System.Drawing.Point(580, 28);
this.groupBoxTools.Name = "groupBoxTools";
this.groupBoxTools.Size = new System.Drawing.Size(220, 504);
this.groupBoxTools.Size = new System.Drawing.Size(220, 637);
this.groupBoxTools.TabIndex = 0;
this.groupBoxTools.TabStop = false;
this.groupBoxTools.Text = "Tools";
//
// ButtonSortByType
//
this.ButtonSortByType.Location = new System.Drawing.Point(7, 456);
this.ButtonSortByType.Name = "ButtonSortByType";
this.ButtonSortByType.Size = new System.Drawing.Size(207, 29);
this.ButtonSortByType.TabIndex = 9;
this.ButtonSortByType.Text = "Sort By Type";
this.ButtonSortByType.UseVisualStyleBackColor = true;
this.ButtonSortByType.Click += new System.EventHandler(this.ButtonSortByType_Click);
//
// groupBox1
//
this.groupBox1.Controls.Add(this.buttonDeleteMap);
this.groupBox1.Controls.Add(this.listBoxMaps);
this.groupBox1.Controls.Add(this.buttonAddMap);
this.groupBox1.Controls.Add(this.textBoxNewMapName);
this.groupBox1.Controls.Add(this.comboBoxSelectorMap);
this.groupBox1.Location = new System.Drawing.Point(6, 26);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(208, 250);
this.groupBox1.TabIndex = 8;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Maps";
//
// buttonDeleteMap
//
this.buttonDeleteMap.Location = new System.Drawing.Point(6, 198);
this.buttonDeleteMap.Name = "buttonDeleteMap";
this.buttonDeleteMap.Size = new System.Drawing.Size(196, 29);
this.buttonDeleteMap.TabIndex = 3;
this.buttonDeleteMap.Text = "Delete Map";
this.buttonDeleteMap.UseVisualStyleBackColor = true;
this.buttonDeleteMap.Click += new System.EventHandler(this.buttonDeleteMap_Click);
//
// listBoxMaps
//
this.listBoxMaps.FormattingEnabled = true;
this.listBoxMaps.ItemHeight = 20;
this.listBoxMaps.Location = new System.Drawing.Point(6, 128);
this.listBoxMaps.Name = "listBoxMaps";
this.listBoxMaps.Size = new System.Drawing.Size(196, 64);
this.listBoxMaps.TabIndex = 2;
this.listBoxMaps.SelectedIndexChanged += new System.EventHandler(this.listBoxMaps_SelectedIndexChanged);
//
// buttonAddMap
//
this.buttonAddMap.Location = new System.Drawing.Point(6, 93);
this.buttonAddMap.Name = "buttonAddMap";
this.buttonAddMap.Size = new System.Drawing.Size(196, 29);
this.buttonAddMap.TabIndex = 1;
this.buttonAddMap.Text = "Add Map";
this.buttonAddMap.UseVisualStyleBackColor = true;
this.buttonAddMap.Click += new System.EventHandler(this.buttonAddMap_Click);
//
// textBoxNewMapName
//
this.textBoxNewMapName.Location = new System.Drawing.Point(6, 26);
this.textBoxNewMapName.Name = "textBoxNewMapName";
this.textBoxNewMapName.Size = new System.Drawing.Size(196, 27);
this.textBoxNewMapName.TabIndex = 0;
//
// comboBoxSelectorMap
//
this.comboBoxSelectorMap.FormattingEnabled = true;
this.comboBoxSelectorMap.Items.AddRange(new object[] {
"Simple Map",
"Spike Map",
"Rail Map"});
this.comboBoxSelectorMap.Location = new System.Drawing.Point(6, 59);
this.comboBoxSelectorMap.Name = "comboBoxSelectorMap";
this.comboBoxSelectorMap.Size = new System.Drawing.Size(196, 28);
this.comboBoxSelectorMap.TabIndex = 0;
//
// buttonLeft
//
this.buttonLeft.BackgroundImage = global::Locomotive.Properties.Resources.left_arrow;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonLeft.Location = new System.Drawing.Point(42, 446);
this.buttonLeft.Location = new System.Drawing.Point(48, 591);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(40, 40);
this.buttonLeft.TabIndex = 7;
@@ -79,7 +169,7 @@
//
this.buttonRight.BackgroundImage = global::Locomotive.Properties.Resources.right_arrow;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonRight.Location = new System.Drawing.Point(134, 446);
this.buttonRight.Location = new System.Drawing.Point(140, 591);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(40, 40);
this.buttonRight.TabIndex = 7;
@@ -90,7 +180,7 @@
//
this.buttonDown.BackgroundImage = global::Locomotive.Properties.Resources.down_arrow;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonDown.Location = new System.Drawing.Point(88, 446);
this.buttonDown.Location = new System.Drawing.Point(94, 591);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(40, 40);
this.buttonDown.TabIndex = 7;
@@ -101,7 +191,7 @@
//
this.buttonUp.BackgroundImage = global::Locomotive.Properties.Resources.up_arrow;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonUp.Location = new System.Drawing.Point(88, 400);
this.buttonUp.Location = new System.Drawing.Point(94, 545);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(40, 40);
this.buttonUp.TabIndex = 6;
@@ -110,7 +200,7 @@
//
// buttonShowOnMap
//
this.buttonShowOnMap.Location = new System.Drawing.Point(7, 282);
this.buttonShowOnMap.Location = new System.Drawing.Point(7, 421);
this.buttonShowOnMap.Name = "buttonShowOnMap";
this.buttonShowOnMap.Size = new System.Drawing.Size(207, 29);
this.buttonShowOnMap.TabIndex = 5;
@@ -120,9 +210,9 @@
//
// buttonShowStorage
//
this.buttonShowStorage.Location = new System.Drawing.Point(7, 247);
this.buttonShowStorage.Location = new System.Drawing.Point(6, 386);
this.buttonShowStorage.Name = "buttonShowStorage";
this.buttonShowStorage.Size = new System.Drawing.Size(207, 29);
this.buttonShowStorage.Size = new System.Drawing.Size(208, 29);
this.buttonShowStorage.TabIndex = 4;
this.buttonShowStorage.Text = "Show Storage";
this.buttonShowStorage.UseVisualStyleBackColor = true;
@@ -130,7 +220,7 @@
//
// buttonRemoveLocomotive
//
this.buttonRemoveLocomotive.Location = new System.Drawing.Point(7, 211);
this.buttonRemoveLocomotive.Location = new System.Drawing.Point(7, 350);
this.buttonRemoveLocomotive.Name = "buttonRemoveLocomotive";
this.buttonRemoveLocomotive.Size = new System.Drawing.Size(207, 30);
this.buttonRemoveLocomotive.TabIndex = 3;
@@ -140,7 +230,7 @@
//
// maskedTextBoxPosition
//
this.maskedTextBoxPosition.Location = new System.Drawing.Point(6, 159);
this.maskedTextBoxPosition.Location = new System.Drawing.Point(6, 317);
this.maskedTextBoxPosition.Mask = "00";
this.maskedTextBoxPosition.Name = "maskedTextBoxPosition";
this.maskedTextBoxPosition.Size = new System.Drawing.Size(208, 27);
@@ -148,7 +238,7 @@
//
// buttonAddLocomotive
//
this.buttonAddLocomotive.Location = new System.Drawing.Point(6, 96);
this.buttonAddLocomotive.Location = new System.Drawing.Point(6, 282);
this.buttonAddLocomotive.Name = "buttonAddLocomotive";
this.buttonAddLocomotive.Size = new System.Drawing.Size(208, 29);
this.buttonAddLocomotive.TabIndex = 1;
@@ -156,41 +246,86 @@
this.buttonAddLocomotive.UseVisualStyleBackColor = true;
this.buttonAddLocomotive.Click += new System.EventHandler(this.buttonAddLocomotive_Click);
//
// comboBoxSelectorMap
//
this.comboBoxSelectorMap.FormattingEnabled = true;
this.comboBoxSelectorMap.Items.AddRange(new object[] {
"Simple Map",
"Spike Map",
"Rail Map"});
this.comboBoxSelectorMap.Location = new System.Drawing.Point(6, 39);
this.comboBoxSelectorMap.Name = "comboBoxSelectorMap";
this.comboBoxSelectorMap.Size = new System.Drawing.Size(208, 28);
this.comboBoxSelectorMap.TabIndex = 0;
this.comboBoxSelectorMap.SelectedIndexChanged += new System.EventHandler(this.comboBoxSelectorMap_SelectedIndexChanged);
//
// pictureBox
//
this.pictureBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBox.Location = new System.Drawing.Point(0, 0);
this.pictureBox.Location = new System.Drawing.Point(0, 28);
this.pictureBox.Name = "pictureBox";
this.pictureBox.Size = new System.Drawing.Size(580, 504);
this.pictureBox.Size = new System.Drawing.Size(580, 637);
this.pictureBox.TabIndex = 1;
this.pictureBox.TabStop = false;
//
// menuStrip
//
this.menuStrip.ImageScalingSize = new System.Drawing.Size(20, 20);
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(800, 28);
this.menuStrip.TabIndex = 2;
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.saveToolStripMenuItem,
this.loadToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(46, 24);
this.fileToolStripMenuItem.Text = "File";
//
// saveToolStripMenuItem
//
this.saveToolStripMenuItem.Name = "saveToolStripMenuItem";
this.saveToolStripMenuItem.Size = new System.Drawing.Size(125, 26);
this.saveToolStripMenuItem.Text = "Save";
this.saveToolStripMenuItem.Click += new System.EventHandler(this.saveToolStripMenuItem_Click);
//
// loadToolStripMenuItem
//
this.loadToolStripMenuItem.Name = "loadToolStripMenuItem";
this.loadToolStripMenuItem.Size = new System.Drawing.Size(125, 26);
this.loadToolStripMenuItem.Text = "Load";
this.loadToolStripMenuItem.Click += new System.EventHandler(this.loadToolStripMenuItem_Click);
//
// loadFileDialog
//
this.loadFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
this.saveFileDialog.Filter = "txt file | *.txt";
//
// ButtonSortByColor
//
this.ButtonSortByColor.Location = new System.Drawing.Point(7, 491);
this.ButtonSortByColor.Name = "ButtonSortByColor";
this.ButtonSortByColor.Size = new System.Drawing.Size(207, 29);
this.ButtonSortByColor.TabIndex = 10;
this.ButtonSortByColor.Text = "Sort By Color";
this.ButtonSortByColor.UseVisualStyleBackColor = true;
this.ButtonSortByColor.Click += new System.EventHandler(this.ButtonSortByColor_Click);
//
// FormMapWithSetLocomotives
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 504);
this.ClientSize = new System.Drawing.Size(800, 665);
this.Controls.Add(this.pictureBox);
this.Controls.Add(this.groupBoxTools);
this.Controls.Add(this.menuStrip);
this.MainMenuStrip = this.menuStrip;
this.Name = "FormMapWithSetLocomotives";
this.Text = "FormMapWithSetLocomotives";
this.groupBoxTools.ResumeLayout(false);
this.groupBoxTools.PerformLayout();
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
@@ -208,5 +343,18 @@
private Button buttonDown;
private Button buttonRight;
private Button buttonLeft;
private GroupBox groupBox1;
private TextBox textBoxNewMapName;
private Button buttonAddMap;
private Button buttonDeleteMap;
private ListBox listBoxMaps;
private MenuStrip menuStrip;
private ToolStripMenuItem fileToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private OpenFileDialog loadFileDialog;
private SaveFileDialog saveFileDialog;
private Button ButtonSortByType;
private Button ButtonSortByColor;
}
}

View File

@@ -1,4 +1,6 @@
using System;
using Serilog;
using Serilog.Formatting.Compact;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
@@ -12,104 +14,186 @@ namespace Locomotive
{
public partial class FormMapWithSetLocomotives : Form
{
/// Объект от класса карты с набором объектов
private MapWithSetLocomotivesGeneric<DrawningObjectLocomotive, AbstractMap> _mapLocomotivesCollectionGeneric;
/// Словарь для выпадающего списка
private readonly Dictionary<string, AbstractMap> _mapsDict = new()
{
{ "Simple Map", new SimpleMap() },
{ "Spike Map", new SpikeMap() },
{ "Rail Map", new RailroadMap() }
};
/// Объект от коллекции карт
private readonly MapsCollection _mapsCollection;
/// Конструктор
public FormMapWithSetLocomotives()
{
InitializeComponent();
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
comboBoxSelectorMap.Items.Clear();
foreach (var elem in _mapsDict)
{
comboBoxSelectorMap.Items.Add(elem.Key);
}
}
/// Заполнение listBoxMaps
private void ReloadMaps()
{
int index = listBoxMaps.SelectedIndex;
listBoxMaps.Items.Clear();
for (int i = 0; i < _mapsCollection.Keys.Count; i++)
{
listBoxMaps.Items.Add(_mapsCollection.Keys[i]);
}
if (listBoxMaps.Items.Count > 0 && (index == -1 || index >= listBoxMaps.Items.Count))
{
listBoxMaps.SelectedIndex = 0;
}
else if (listBoxMaps.Items.Count > 0 && index > -1 && index < listBoxMaps.Items.Count)
{
listBoxMaps.SelectedIndex = index;
}
}
/// Добавление карты
private void buttonAddMap_Click(object sender, EventArgs e)
{
if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text))
{
MessageBox.Show("Not all data is complete", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text))
{
MessageBox.Show("No such map", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]);
Log.Information($"Map {textBoxNewMapName.Text} added");
ReloadMaps();
}
/// Выбор карты
private void comboBoxSelectorMap_SelectedIndexChanged(object sender, EventArgs e)
private void listBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{
AbstractMap map = null;
switch (comboBoxSelectorMap.Text)
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
Log.Information($"Map switched to {listBoxMaps.SelectedItem?.ToString() ?? string.Empty}");
}
/// Удаление карты
private void buttonDeleteMap_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
case "Simple Map":
map = new SimpleMap();
break;
case "Spike Map":
map = new SpikeMap();
break;
case "Rail Map":
map = new RailroadMap();
break;
return;
}
if (map != null)
if (MessageBox.Show($"Delete map {listBoxMaps.SelectedItem}?","Deleting", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_mapLocomotivesCollectionGeneric = new MapWithSetLocomotivesGeneric<DrawningObjectLocomotive, AbstractMap>
(pictureBox.Width, pictureBox.Height, map);
}
else
{
_mapLocomotivesCollectionGeneric = null;
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
Log.Information($"Map {listBoxMaps.SelectedItem?.ToString() ?? string.Empty} deleted");
ReloadMaps();
}
}
/// Добавление объекта
private void buttonAddLocomotive_Click(object sender, EventArgs e)
{
if (_mapLocomotivesCollectionGeneric == null)
var formCarConfig = new FormLocomotiveConfig();
formCarConfig.AddEvent(new (AddLocomotive));
formCarConfig.Show();
}
private void AddLocomotive(DrawningLocomotive locomotive)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
FormLocomotive form = new();
if (form.ShowDialog() == DialogResult.OK)
try
{
DrawningObjectLocomotive locomotive = new(form.SelectedLocomotive);
if (_mapLocomotivesCollectionGeneric + locomotive != -1)
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectLocomotive(locomotive) != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _mapLocomotivesCollectionGeneric.ShowSet();
MessageBox.Show("Object added");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
Log.Information($"Object {locomotive} added");
}
else
{
MessageBox.Show("Не удалось добавить объект");
MessageBox.Show("Failed to add object");
}
}
catch(StorageOverflowException ex)
{
MessageBox.Show($"Storage overflow error: {ex.Message}");
}
catch (Exception ex)
{
MessageBox.Show($"Unknown error: {ex.Message}");
}
}
/// Удаление объекта
private void buttonRemoveLocomotive_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text))
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
if (MessageBox.Show("Remove object?", "Removing", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_mapLocomotivesCollectionGeneric - pos is not null)
try
{
MessageBox.Show("Объект удален");
pictureBox.Image = _mapLocomotivesCollectionGeneric.ShowSet();
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
{
MessageBox.Show("Object removed");
Log.Information($"Locomotive at {pos} deleted");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
MessageBox.Show("Failed to remove object");
}
}
else
catch(LocomotiveNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show($"Delete error: {ex.Message}");
}
catch (Exception ex)
{
MessageBox.Show($"Unknown error: {ex.Message}");
}
}
/// Вывод набора
private void buttonShowStorage_Click(object sender, EventArgs e)
{
if (_mapLocomotivesCollectionGeneric == null)
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
pictureBox.Image = _mapLocomotivesCollectionGeneric.ShowSet();
pictureBox.Image =
_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
/// Вывод карты
private void buttonShowOnMap_Click(object sender, EventArgs e)
{
if (_mapLocomotivesCollectionGeneric == null)
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
pictureBox.Image = _mapLocomotivesCollectionGeneric.ShowOnMap();
pictureBox.Image =
_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowOnMap();
}
/// Перемещение
private void buttonMove_Click(object sender, EventArgs e)
{
if (_mapLocomotivesCollectionGeneric == null)
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
@@ -131,7 +215,64 @@ namespace Locomotive
dir = Direction.Right;
break;
}
pictureBox.Image = _mapLocomotivesCollectionGeneric.MoveObject(dir);
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].MoveObject(dir);
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_mapsCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Saving success", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
Log.Information($"Saved to {saveFileDialog.FileName}");
}
catch (Exception ex)
{
MessageBox.Show($"Saving error: {ex.Message}", "Result",MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void loadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (loadFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_mapsCollection.LoadData(loadFileDialog.FileName);
MessageBox.Show("Loaded successfully", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
Log.Information($"Loaded from {loadFileDialog.FileName}");
ReloadMaps();
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
catch(Exception ex)
{
MessageBox.Show($"Loading failed + {ex.Message}", "Result", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonSortByType_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].Sort(new LocomotiveCompareByType());
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].Sort(new LocomotiveCompareByColor());
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
}
}

View File

@@ -57,4 +57,16 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="loadFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>144, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>311, 17</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>25</value>
</metadata>
</root>

View File

@@ -6,7 +6,7 @@ using System.Threading.Tasks;
namespace Locomotive
{
internal interface IDrawningObject
internal interface IDrawningObject : IEquatable<IDrawningObject>
{
/// Шаг перемещения объекта
public float Step { get; }
@@ -19,5 +19,7 @@ namespace Locomotive
/// Получение текущей позиции объекта
(float Left, float Right, float Top, float Bottom) GetCurrentPosition();
// Получение информации по объекту
string getInfo();
}
}

View File

@@ -8,6 +8,13 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Serilog" Version="2.12.0" />
<PackageReference Include="Serilog.Formatting.Compact" Version="1.1.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="4.1.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

@@ -0,0 +1,78 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Locomotive
{
internal class LocomotiveCompareByColor : IComparer<IDrawningObject>
{
public int Compare(IDrawningObject? x, IDrawningObject? y)
{
if (x == null && y == null)
{
return 0;
}
if (x == null && y != null)
{
return 1;
}
if (x != null && y == null)
{
return -1;
}
var xLocomotive = x as DrawningObjectLocomotive;
var yLocomotive = y as DrawningObjectLocomotive;
if (xLocomotive == null && yLocomotive == null)
{
return 0;
}
if (xLocomotive == null && yLocomotive != null)
{
return 1;
}
if (xLocomotive != null && yLocomotive == null)
{
return -1;
}
if (xLocomotive.GetLocomotive.Locomotive.BodyColor.R.CompareTo(yLocomotive.GetLocomotive.Locomotive.BodyColor.R) != 0)
{
return xLocomotive.GetLocomotive.Locomotive.BodyColor.R.CompareTo(yLocomotive.GetLocomotive.Locomotive.BodyColor.R);
}
if (xLocomotive.GetLocomotive.Locomotive.BodyColor.G.CompareTo(yLocomotive.GetLocomotive.Locomotive.BodyColor.G) != 0)
{
return xLocomotive.GetLocomotive.Locomotive.BodyColor.G.CompareTo(yLocomotive.GetLocomotive.Locomotive.BodyColor.G);
}
if (xLocomotive.GetLocomotive.Locomotive.BodyColor.B.CompareTo(yLocomotive.GetLocomotive.Locomotive.BodyColor.B) != 0)
{
return xLocomotive.GetLocomotive.Locomotive.BodyColor.B.CompareTo(yLocomotive.GetLocomotive.Locomotive.BodyColor.B);
}
if (xLocomotive.GetLocomotive.Locomotive is EntityWarmlyLocomotive xWarmlyEntity && yLocomotive.GetLocomotive.Locomotive is EntityWarmlyLocomotive yWarmlyEntity)
{
if (xWarmlyEntity.ExtraColor.R.CompareTo(yWarmlyEntity.ExtraColor.R) != 0)
{
return xWarmlyEntity.ExtraColor.R.CompareTo(yWarmlyEntity.ExtraColor.R);
}
if (xWarmlyEntity.ExtraColor.G.CompareTo(yWarmlyEntity.ExtraColor.G) != 0)
{
return xWarmlyEntity.ExtraColor.G.CompareTo(yWarmlyEntity.ExtraColor.G);
}
if (xWarmlyEntity.ExtraColor.B.CompareTo(yWarmlyEntity.ExtraColor.B) != 0)
{
return xWarmlyEntity.ExtraColor.B.CompareTo(yWarmlyEntity.ExtraColor.B);
}
}
var speedCompare = xLocomotive.GetLocomotive.Locomotive.Speed.CompareTo(yLocomotive.GetLocomotive.Locomotive.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return xLocomotive.GetLocomotive.Locomotive.Weight.CompareTo(yLocomotive.GetLocomotive.Locomotive.Weight);
}
}
}

View File

@@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Locomotive
{
internal class LocomotiveCompareByType : IComparer<IDrawningObject>
{
public int Compare(IDrawningObject? x, IDrawningObject? y)
{
if (x == null && y == null)
{
return 0;
}
if (x == null && y != null)
{
return 1;
}
if (x != null && y == null)
{
return -1;
}
var xLocomotive = x as DrawningObjectLocomotive;
var yLocomotive = y as DrawningObjectLocomotive;
if (xLocomotive == null && yLocomotive == null)
{
return 0;
}
if (xLocomotive == null && yLocomotive != null)
{
return 1;
}
if (xLocomotive != null && yLocomotive == null)
{
return -1;
}
if (xLocomotive.GetLocomotive.GetType().Name != yLocomotive.GetLocomotive.GetType().Name)
{
if (xLocomotive.GetLocomotive.GetType().Name == "DrawningLocomotive")
{
return -1;
}
return 1;
}
var speedCompare = xLocomotive.GetLocomotive.Locomotive.Speed.CompareTo(yLocomotive.GetLocomotive.Locomotive.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return xLocomotive.GetLocomotive.Locomotive.Weight.CompareTo(yLocomotive.GetLocomotive.Locomotive.Weight);
}
}
}

View File

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

View File

@@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace Locomotive
{
internal class MapWithSetLocomotivesGeneric <T, U>
where T : class, IDrawningObject
where T : class, IDrawningObject, IEquatable<T>
where U : AbstractMap
{
/// Ширина окна отрисовки
@@ -15,9 +15,9 @@ namespace Locomotive
/// Высота окна отрисовки
private readonly int _pictureHeight;
/// Размер занимаемого объектом места (ширина)
private readonly int _placeSizeWidth = 210;
private readonly int _placeSizeWidth = 150;
/// Размер занимаемого объектом места (высота)
private readonly int _placeSizeHeight = 90;
private readonly int _placeSizeHeight = 150;
/// Набор объектов
private readonly SetLocomotivesGeneric<T> _setLocomotives;
/// Карта
@@ -55,13 +55,9 @@ namespace Locomotive
public Bitmap ShowOnMap()
{
Shaking();
for (int i = 0; i < _setLocomotives.Count; i++)
foreach (var locomotive in _setLocomotives.GetLocomotives())
{
var locomotive = _setLocomotives.Get(i);
if (locomotive != null)
{
return _map.CreateMap(_pictureWidth, _pictureHeight, locomotive);
}
return _map.CreateMap(_pictureWidth, _pictureHeight, locomotive);
}
return new(_pictureWidth, _pictureHeight);
}
@@ -80,11 +76,11 @@ namespace Locomotive
int j = _setLocomotives.Count - 1;
for (int i = 0; i < _setLocomotives.Count; i++)
{
if (_setLocomotives.Get(i) == null)
if (_setLocomotives[i] == null)
{
for (; j > i; j--)
{
var locomotive = _setLocomotives.Get(j);
var locomotive = _setLocomotives[j];
if (locomotive != null)
{
_setLocomotives.Insert(locomotive, i);
@@ -142,17 +138,17 @@ namespace Locomotive
/// Метод прорисовки объектов
private void DrawLocomotives(Graphics g)
{
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
int width = _pictureWidth / _placeSizeWidth - 1;
int height = _pictureHeight / _placeSizeHeight - 1;
int curWidth = 0;
int curHeight = 0;
for (int i = 0; i < _setLocomotives.Count; i++)
foreach (var locomotive in _setLocomotives.GetLocomotives())
{
// установка позиции
_setLocomotives.Get(i)?.SetObject(curWidth * _placeSizeWidth + 10, curHeight * _placeSizeHeight + 15, _pictureWidth, _pictureHeight);
_setLocomotives.Get(i)?.DrawningObject(g);
locomotive?.SetObject(curWidth * _placeSizeWidth + 10, curHeight * _placeSizeHeight + 80, _pictureWidth, _pictureHeight);
locomotive?.DrawningObject(g);
if (curWidth < width) curWidth++;
else
{
@@ -162,5 +158,29 @@ namespace Locomotive
}
}
/// Получение данных в виде строки
public string GetData(char separatorType, char separatorData)
{
string data = $"{_map.GetType().Name}{separatorType}";
foreach (var locomotive in _setLocomotives.GetLocomotives())
{
data += $"{locomotive.getInfo()}{separatorData}";
}
return data;
}
/// Загрузка списка из массива строк
public void LoadData(string[] records)
{
foreach (var rec in records.Reverse())
{
_setLocomotives.Insert(DrawningObjectLocomotive.Create(rec) as T);
}
}
public void Sort(IComparer<T> comparer)
{
_setLocomotives.SortSet(comparer);
}
}
}

View File

@@ -0,0 +1,124 @@
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Locomotive
{
internal class MapsCollection
{
/// Словарь (хранилище) с картами
readonly Dictionary<string, MapWithSetLocomotivesGeneric<IDrawningObject,
AbstractMap>> _mapStorages;
/// Возвращение списка названий карт
public List<string> Keys => _mapStorages.Keys.ToList();
/// Ширина окна отрисовки
private readonly int _pictureWidth;
/// Высота окна отрисовки
private readonly int _pictureHeight;
// Сепараторы
private readonly char separatorDict = '|';
private readonly char separatorData = ';';
/// Конструктор
public MapsCollection(int pictureWidth, int pictureHeight)
{
_mapStorages = new Dictionary<string,
MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
/// Добавление карты
public void AddMap(string name, AbstractMap map)
{
// Логика для добавления
if (!_mapStorages.ContainsKey(name)) _mapStorages.Add(name, new MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
}
/// Удаление карты
public void DelMap(string name)
{
// Логика для удаления
if (_mapStorages.ContainsKey(name)) _mapStorages.Remove(name);
}
/// Доступ к парковке
public MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap> this[string ind]
{
get
{
// Логика получения объекта
if (_mapStorages.ContainsKey(ind)) return _mapStorages[ind];
return null;
}
}
/// Сохранение информации по локомотивам в хранилище в файл
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
using (FileStream fs = new(filename, FileMode.Create))
using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
{
sw.WriteLine("MapsCollection");
foreach (var storage in _mapStorages)
{
sw.WriteLine(
$"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}"
);
}
}
}
/// Загрузка нформации по локомотивам в депо из файла
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
Log.Warning($"FileNotFoundException {filename}");
throw new FileNotFoundException("Файл не найден");
}
using (FileStream fs = new(filename, FileMode.Open))
using (StreamReader sr = new StreamReader(fs, Encoding.UTF8))
{
string curLine = sr.ReadLine();
if (!curLine.Contains("MapsCollection"))
{
Log.Warning($"FileFormatException");
throw new FileFormatException("Формат данных в файле неправильный");
}
_mapStorages.Clear();
while ((curLine = sr.ReadLine()) != null)
{
var elems = curLine.Split(separatorDict);
AbstractMap map = null;
switch (elems[1])
{
case "Simple Map":
map = new SimpleMap();
break;
case "Spike Map":
map = new SpikeMap();
break;
case "Rail Map":
map = new RailroadMap();
break;
}
_mapStorages.Add(elems[0], new MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[elems[0]].LoadData(elems[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
}
}
}
}
}

View File

@@ -1,3 +1,5 @@
using Serilog;
namespace Locomotive
{
internal static class Program
@@ -10,6 +12,9 @@ namespace Locomotive
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
Log.Logger = new LoggerConfiguration().WriteTo.File(new Serilog.Formatting.Compact.CompactJsonFormatter(), "C:\\secondCourse\\OOP\\ProjectLomotive\\Locomotive\\log.clef").CreateLogger();
ApplicationConfiguration.Initialize();
Application.Run(new FormMapWithSetLocomotives());
}

View File

@@ -1,4 +1,5 @@
using System;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -7,16 +8,20 @@ using System.Threading.Tasks;
namespace Locomotive
{
internal class SetLocomotivesGeneric <T>
where T : class
where T : class, IEquatable<T>
{
private readonly T[] _places;
/// Список хранимых объектов
private readonly List<T> _places;
/// Количество объектов в массиве
public int Count => _places.Length;
public int Count => _places.Count;
// Ограничение на количество
private readonly int _maxCount;
/// Конструктор
public SetLocomotivesGeneric(int count)
{
_places = new T[count];
_maxCount = count;
_places = new List<T>();
}
/// Добавление объекта в набор
public int Insert(T locomotive)
@@ -26,53 +31,61 @@ namespace Locomotive
/// Добавление объекта в набор на конкретную позицию
public int Insert(T locomotive, int position)
{
if (position >= _places.Length|| position < 0) return -1;
if (_places[position] == null)
{
_places[position] = locomotive;
return position;
if (_places.Contains(locomotive)) return -1; // Проверка на уникальность
if (position < 0) return -1;
if (Count >= _maxCount) {
Log.Warning("StorageOverflowException");
throw new StorageOverflowException(_maxCount);
}
_places.Insert(position, locomotive);
int emptyEl = -1;
for (int i = position + 1; i < Count; i++)
{
if (_places[i] == null)
{
emptyEl = i;
break;
}
}
if (emptyEl == -1)
{
return -1;
}
for (int i = emptyEl; i > position; i--)
{
_places[i] = _places[i - 1];
}
_places[position] = locomotive;
return position;
}
/// Удаление объекта из набора с конкретной позиции
public T Remove(int position)
{
if (position >= _places.Length || position < 0) return null;
if (position >= _maxCount || position < 0) return null;
if (_places[position] is null)
{
Log.Warning($"LocomotiveNotFoundException at {position}");
throw new LocomotiveNotFoundException(position);
}
T result = _places[position];
_places[position] = null;
_places[position] = null;
return result;
}
/// Получение объекта из набора по позиции
public T Get(int position)
// Индексатор
public T this[int position]
{
if (position >= _places.Length || position < 0)
get
{
return null;
if (position >= _maxCount || position < 0) return null;
return _places[position];
}
set
{
if (position >= _maxCount || position < 0) return;
Insert(value, position);
}
return _places[position];
}
/// Проход по набору до первого пустого
public IEnumerable<T> GetLocomotives()
{
foreach (var locomotive in _places)
{
yield return locomotive;
}
}
public void SortSet(IComparer<T> comparer)
{
if (comparer == null)
{
return;
}
_places.Sort(comparer);
}
}
}

View File

@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Locomotive
{
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 context) : base(info, context) { }
}
}

17
Locomotive/log.clef Normal file
View File

@@ -0,0 +1,17 @@
{"@t":"2022-11-21T15:23:13.2775821Z","@mt":"Map lalaland added"}
{"@t":"2022-11-21T15:23:13.3466012Z","@mt":"Map switched to lalaland"}
{"@t":"2022-11-21T15:23:31.6565447Z","@mt":"Object Locomotive.DrawningLocomotive added"}
{"@t":"2022-11-21T15:23:57.7770111Z","@mt":"Object Locomotive.DrawningLocomotive added"}
{"@t":"2022-11-21T15:25:01.0533266Z","@mt":"Map lalaland added"}
{"@t":"2022-11-21T15:25:01.0794891Z","@mt":"Map switched to lalaland"}
{"@t":"2022-11-21T15:25:01.4998647Z","@mt":"Map switched to lalaland"}
{"@t":"2022-11-21T15:25:06.1595618Z","@mt":"Object Locomotive.DrawningLocomotive added"}
{"@t":"2022-11-21T15:25:18.9994738Z","@mt":"Object Locomotive.DrawningLocomotive added"}
{"@t":"2022-11-21T15:25:31.8129464Z","@mt":"Map lalaland added"}
{"@t":"2022-11-21T15:25:31.8344280Z","@mt":"Map switched to lalaland"}
{"@t":"2022-11-21T15:25:37.1362070Z","@mt":"Object Locomotive.DrawningLocomotive added"}
{"@t":"2022-11-21T15:25:46.1930394Z","@mt":"Object Locomotive.DrawningLocomotive added"}
{"@t":"2022-11-21T15:26:02.0790751Z","@mt":"Object Locomotive.DrawningLocomotive added"}
{"@t":"2022-11-21T15:26:24.6631252Z","@mt":"Object Locomotive.DrawningWarmlyLocomotive added"}
{"@t":"2022-11-21T15:26:31.0236570Z","@mt":"Object Locomotive.DrawningLocomotive added"}
{"@t":"2022-11-21T15:26:36.0331011Z","@mt":"Object Locomotive.DrawningWarmlyLocomotive added"}