13 Commits

Author SHA1 Message Date
crum61kg
6a6abe240f Сравнение объектов 2023-02-14 23:21:28 +04:00
crum61kg
3473802309 меняю nlog на serilog + 2023-02-14 23:06:15 +04:00
crum61kg
2a2bac1b20 Изменения 2023-02-08 23:32:38 +04:00
crum61kg
86398dc418 Логирование 2023-02-08 21:48:34 +04:00
crum61kg
7884e5e29c Генерация ошибок 2023-02-08 21:21:52 +04:00
crum61kg
2ede363766 Изменение лаб_6 2023-02-08 20:43:26 +04:00
crum61kg
d9f1f47750 Изменения 2023-01-23 03:05:28 +04:00
crum61kg
a51a6a2102 Event work 2023-01-23 02:12:44 +04:00
crum61kg
c58ecbd47e Add config form 2023-01-23 02:00:16 +04:00
crum61kg
c7de4f3d1d Изменения 2023-01-23 00:00:11 +04:00
crum61kg
68db88d4c4 Этап 3. Форма 2023-01-22 03:02:52 +04:00
crum61kg
60d8898b17 Этап 2. Класс MapsCollection 2023-01-22 01:42:02 +04:00
crum61kg
2e12e1f2e1 Этап 1. Смена массива на список 2023-01-22 01:35:09 +04:00
21 changed files with 1556 additions and 201 deletions

View File

@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.PortableExecutable;
using System.Text;
using System.Threading.Tasks;
@@ -52,5 +53,15 @@ namespace WarmlyShip
}
}
public void SetDopColor(Color color)
{
Ship = Ship as EntityLiner;
if (Ship is not null)
{
Ship = new EntityLiner(Ship.Speed, Ship.Weight, Ship.BodyColor,
color, (Ship as EntityLiner).SwimmingPool, (Ship as EntityLiner).DopDeck);
}
}
}
}

View File

@@ -36,5 +36,40 @@ namespace WarmlyShip
{
_ship.DrawTransport(g);
}
public string GetInfo() => _ship?.GetDataForSave();
public static IDrawningObject Create(string data) => new DrawningObjectShip(data.CreateDrawningShip());
public bool Equals(IDrawningObject? other)
{
if (other == null)
{
return false;
}
var otherShip = other as DrawningObjectShip;
if (otherShip == null)
{
return false;
}
var ship = _ship.Ship;
var otherShipShip = otherShip._ship.Ship;
if (ship.Speed != otherShipShip.Speed)
{
return false;
}
if (ship.Weight != otherShipShip.Weight)
{
return false;
}
if (ship.BodyColor != otherShipShip.BodyColor)
{
return false;
}
// TODO доделать проверки в случае продвинутого объекта
return true;
}
}
}

View File

@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.PortableExecutable;
using System.Text;
using System.Threading.Tasks;
@@ -199,5 +200,20 @@ namespace WarmlyShip
{
return (_startPosX, _startPosY, _startPosX + _shipWidth, _startPosY + _shipHeight);
}
public virtual void SetBaseColor(Color color)
{
if (Ship is EntityLiner)
{
Ship = (EntityLiner)Ship;
if (Ship is not null)
{
Ship = new EntityLiner(Ship.Speed, Ship.Weight, color, (Ship as EntityLiner).DopColor, (Ship as EntityLiner).SwimmingPool, (Ship as EntityLiner).DopDeck);
return;
}
}
Ship = new EntityShip(Ship.Speed, Ship.Weight, color);
}
}
}

View File

@@ -0,0 +1,54 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip
{
internal static class ExtentionShip
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public static DrawningShip CreateDrawningShip(this string info)
{
string[] strs = info.Split(_separatorForObject);
if (strs.Length == 3)
{
return new DrawningShip(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]));
}
if (strs.Length == 6)
{
return new DrawningLiner(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;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningCar"></param>
/// <returns></returns>
public static string GetDataForSave(this DrawningShip drawningShip)
{
var ship = drawningShip.Ship;
var str =
$"{ship.Speed}{_separatorForObject}{ship.Weight}{_separatorForObject}{ship.BodyColor.Name}";
if (ship is not EntityLiner liner)
{
return str;
}
return $"{str}{_separatorForObject}{liner.DopColor.Name}{_separatorForObject}{liner.SwimmingPool}{_separatorForObject}{liner.DopDeck}";
}
}
}

View File

@@ -0,0 +1,360 @@
namespace WarmlyShip
{
partial class FormLinerConfig
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
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.panelBlue = new System.Windows.Forms.Panel();
this.panelGreen = new System.Windows.Forms.Panel();
this.panelRed = new System.Windows.Forms.Panel();
this.checkBoxDopDeck = new System.Windows.Forms.CheckBox();
this.checkBoxSwimmingPool = 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.pictureBoxObject = new System.Windows.Forms.PictureBox();
this.panelObject = new System.Windows.Forms.Panel();
this.buttonCancel = new System.Windows.Forms.Button();
this.buttonAdd = new System.Windows.Forms.Button();
this.labelDopColor = new System.Windows.Forms.Label();
this.labelBaseColor = new System.Windows.Forms.Label();
this.groupBoxConfig.SuspendLayout();
this.groupBoxColors.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).BeginInit();
this.panelObject.SuspendLayout();
this.SuspendLayout();
//
// groupBoxConfig
//
this.groupBoxConfig.Controls.Add(this.labelModifiedObject);
this.groupBoxConfig.Controls.Add(this.labelSimpleObject);
this.groupBoxConfig.Controls.Add(this.groupBoxColors);
this.groupBoxConfig.Controls.Add(this.checkBoxDopDeck);
this.groupBoxConfig.Controls.Add(this.checkBoxSwimmingPool);
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(522, 204);
this.groupBoxConfig.TabIndex = 0;
this.groupBoxConfig.TabStop = false;
this.groupBoxConfig.Text = "Параметры";
//
// labelModifiedObject
//
this.labelModifiedObject.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelModifiedObject.Location = new System.Drawing.Point(419, 148);
this.labelModifiedObject.Name = "labelModifiedObject";
this.labelModifiedObject.Size = new System.Drawing.Size(86, 33);
this.labelModifiedObject.TabIndex = 8;
this.labelModifiedObject.Text = "Продвинутый";
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(321, 148);
this.labelSimpleObject.Name = "labelSimpleObject";
this.labelSimpleObject.Size = new System.Drawing.Size(92, 33);
this.labelSimpleObject.TabIndex = 7;
this.labelSimpleObject.Text = "Простой";
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.panelBlue);
this.groupBoxColors.Controls.Add(this.panelGreen);
this.groupBoxColors.Controls.Add(this.panelRed);
this.groupBoxColors.Location = new System.Drawing.Point(321, 22);
this.groupBoxColors.Name = "groupBoxColors";
this.groupBoxColors.Size = new System.Drawing.Size(192, 115);
this.groupBoxColors.TabIndex = 6;
this.groupBoxColors.TabStop = false;
this.groupBoxColors.Text = "Цвета";
//
// panelPurple
//
this.panelPurple.BackColor = System.Drawing.Color.Purple;
this.panelPurple.Location = new System.Drawing.Point(144, 63);
this.panelPurple.Name = "panelPurple";
this.panelPurple.Size = new System.Drawing.Size(40, 40);
this.panelPurple.TabIndex = 6;
this.panelPurple.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelBlack
//
this.panelBlack.BackColor = System.Drawing.Color.Black;
this.panelBlack.Location = new System.Drawing.Point(98, 63);
this.panelBlack.Name = "panelBlack";
this.panelBlack.Size = new System.Drawing.Size(40, 40);
this.panelBlack.TabIndex = 1;
this.panelBlack.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelGray
//
this.panelGray.BackColor = System.Drawing.Color.Gray;
this.panelGray.Location = new System.Drawing.Point(52, 63);
this.panelGray.Name = "panelGray";
this.panelGray.Size = new System.Drawing.Size(40, 40);
this.panelGray.TabIndex = 5;
this.panelGray.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelWhite
//
this.panelWhite.BackColor = System.Drawing.Color.White;
this.panelWhite.Location = new System.Drawing.Point(6, 63);
this.panelWhite.Name = "panelWhite";
this.panelWhite.Size = new System.Drawing.Size(40, 40);
this.panelWhite.TabIndex = 4;
this.panelWhite.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelYellow
//
this.panelYellow.BackColor = System.Drawing.Color.Yellow;
this.panelYellow.Location = new System.Drawing.Point(144, 17);
this.panelYellow.Name = "panelYellow";
this.panelYellow.Size = new System.Drawing.Size(40, 40);
this.panelYellow.TabIndex = 3;
this.panelYellow.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelBlue
//
this.panelBlue.BackColor = System.Drawing.Color.Blue;
this.panelBlue.Location = new System.Drawing.Point(98, 17);
this.panelBlue.Name = "panelBlue";
this.panelBlue.Size = new System.Drawing.Size(40, 40);
this.panelBlue.TabIndex = 2;
this.panelBlue.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelGreen
//
this.panelGreen.BackColor = System.Drawing.Color.Green;
this.panelGreen.Location = new System.Drawing.Point(52, 17);
this.panelGreen.Name = "panelGreen";
this.panelGreen.Size = new System.Drawing.Size(40, 40);
this.panelGreen.TabIndex = 1;
this.panelGreen.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelRed
//
this.panelRed.BackColor = System.Drawing.Color.Red;
this.panelRed.Location = new System.Drawing.Point(6, 17);
this.panelRed.Name = "panelRed";
this.panelRed.Size = new System.Drawing.Size(40, 40);
this.panelRed.TabIndex = 0;
this.panelRed.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// checkBoxDopDeck
//
this.checkBoxDopDeck.AutoSize = true;
this.checkBoxDopDeck.Location = new System.Drawing.Point(15, 144);
this.checkBoxDopDeck.Name = "checkBoxDopDeck";
this.checkBoxDopDeck.Size = new System.Drawing.Size(264, 19);
this.checkBoxDopDeck.TabIndex = 5;
this.checkBoxDopDeck.Text = "Признак наличия дополнительной палубы";
this.checkBoxDopDeck.UseVisualStyleBackColor = true;
//
// checkBoxSwimmingPool
//
this.checkBoxSwimmingPool.AutoSize = true;
this.checkBoxSwimmingPool.Location = new System.Drawing.Point(15, 109);
this.checkBoxSwimmingPool.Name = "checkBoxSwimmingPool";
this.checkBoxSwimmingPool.Size = new System.Drawing.Size(177, 19);
this.checkBoxSwimmingPool.TabIndex = 4;
this.checkBoxSwimmingPool.Text = "Признак наличия бассейна";
this.checkBoxSwimmingPool.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
this.numericUpDownWeight.Location = new System.Drawing.Point(74, 64);
this.numericUpDownWeight.Name = "numericUpDownWeight";
this.numericUpDownWeight.Size = new System.Drawing.Size(120, 23);
this.numericUpDownWeight.TabIndex = 3;
//
// labelWeight
//
this.labelWeight.AutoSize = true;
this.labelWeight.Location = new System.Drawing.Point(15, 64);
this.labelWeight.Name = "labelWeight";
this.labelWeight.Size = new System.Drawing.Size(29, 15);
this.labelWeight.TabIndex = 2;
this.labelWeight.Text = "Вес:";
//
// numericUpDownSpeed
//
this.numericUpDownSpeed.Location = new System.Drawing.Point(74, 28);
this.numericUpDownSpeed.Name = "numericUpDownSpeed";
this.numericUpDownSpeed.Size = new System.Drawing.Size(120, 23);
this.numericUpDownSpeed.TabIndex = 1;
//
// labelSpeed
//
this.labelSpeed.AutoSize = true;
this.labelSpeed.Location = new System.Drawing.Point(6, 30);
this.labelSpeed.Name = "labelSpeed";
this.labelSpeed.Size = new System.Drawing.Size(62, 15);
this.labelSpeed.TabIndex = 0;
this.labelSpeed.Text = "Скорость:";
//
// pictureBoxObject
//
this.pictureBoxObject.Location = new System.Drawing.Point(14, 48);
this.pictureBoxObject.Name = "pictureBoxObject";
this.pictureBoxObject.Size = new System.Drawing.Size(192, 105);
this.pictureBoxObject.TabIndex = 1;
this.pictureBoxObject.TabStop = false;
//
// panelObject
//
this.panelObject.AllowDrop = true;
this.panelObject.Controls.Add(this.buttonCancel);
this.panelObject.Controls.Add(this.buttonAdd);
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(540, 12);
this.panelObject.Name = "panelObject";
this.panelObject.Size = new System.Drawing.Size(220, 204);
this.panelObject.TabIndex = 2;
this.panelObject.DragDrop += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragDrop);
this.panelObject.DragEnter += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragEnter);
this.panelObject.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(112, 159);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(75, 23);
this.buttonCancel.TabIndex = 5;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
//
// buttonAdd
//
this.buttonAdd.Location = new System.Drawing.Point(31, 159);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(75, 23);
this.buttonAdd.TabIndex = 4;
this.buttonAdd.Text = "Добавить";
this.buttonAdd.UseVisualStyleBackColor = true;
this.buttonAdd.Click += new System.EventHandler(this.ButtonOk_Click);
//
// labelDopColor
//
this.labelDopColor.AllowDrop = true;
this.labelDopColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelDopColor.Location = new System.Drawing.Point(114, 12);
this.labelDopColor.Name = "labelDopColor";
this.labelDopColor.Size = new System.Drawing.Size(92, 33);
this.labelDopColor.TabIndex = 3;
this.labelDopColor.Text = "Доп.цвет";
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.LabelBaseColor_DragEnter);
//
// labelBaseColor
//
this.labelBaseColor.AllowDrop = true;
this.labelBaseColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelBaseColor.Location = new System.Drawing.Point(14, 12);
this.labelBaseColor.Name = "labelBaseColor";
this.labelBaseColor.Size = new System.Drawing.Size(92, 33);
this.labelBaseColor.TabIndex = 2;
this.labelBaseColor.Text = "Цвет";
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);
//
// FormLinerConfig
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 230);
this.Controls.Add(this.panelObject);
this.Controls.Add(this.groupBoxConfig);
this.Name = "FormLinerConfig";
this.Text = "Создание объекта";
this.groupBoxConfig.ResumeLayout(false);
this.groupBoxConfig.PerformLayout();
this.groupBoxColors.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).EndInit();
this.panelObject.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private GroupBox groupBoxConfig;
private Label labelWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelSpeed;
private NumericUpDown numericUpDownWeight;
private CheckBox checkBoxDopDeck;
private CheckBox checkBoxSwimmingPool;
private GroupBox groupBoxColors;
private Panel panelPurple;
private Panel panelBlack;
private Panel panelGray;
private Panel panelWhite;
private Panel panelYellow;
private Panel panelBlue;
private Panel panelGreen;
private Panel panelRed;
private Label labelModifiedObject;
private Label labelSimpleObject;
private PictureBox pictureBoxObject;
private Panel panelObject;
private Label labelDopColor;
private Label labelBaseColor;
private Button buttonCancel;
private Button buttonAdd;
}
}

View File

@@ -0,0 +1,184 @@
using System;
using System.Collections;
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 WarmlyShip
{
/// <summary>
/// Форма создания объекта
/// </summary>
public partial class FormLinerConfig : Form
{
/// <summary>
/// Переменная-выбранная машина
/// </summary>
DrawningShip _liner = null;
/// <summary>
/// Событие
/// </summary>
private event ShipDelegate EventAddShip;
/// <summary>
/// Конструктор
/// </summary>
public FormLinerConfig()
{
InitializeComponent();
panelBlack.MouseDown += PanelColor_MouseDown;
panelPurple.MouseDown += PanelColor_MouseDown;
panelGray.MouseDown += PanelColor_MouseDown;
panelGreen.MouseDown += PanelColor_MouseDown;
panelRed.MouseDown += PanelColor_MouseDown;
panelWhite.MouseDown += PanelColor_MouseDown;
panelYellow.MouseDown += PanelColor_MouseDown;
panelBlue.MouseDown += PanelColor_MouseDown;
buttonCancel.Click += (sender, e) => Close();
}
/// <summary>
/// Отрисовать машину
/// </summary>
private void DrawLiner()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_liner?.SetPosition(5, 5, pictureBoxObject.Width, pictureBoxObject.Height);
_liner?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
/// <summary>
/// Добавление события
/// </summary>
/// <param name="ev"></param>
public void AddEvent(ShipDelegate ev)
{
if (EventAddShip == null)
{
EventAddShip = new ShipDelegate(ev);
}
else
{
EventAddShip += ev;
}
}
/// <summary>
/// Передаем информацию при нажатии на Label
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label).DoDragDrop((sender as Label).Name,DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></par
private void PanelObject_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
/// <summary>
/// Действия при приеме перетаскиваемой информации
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelObject_DragDrop(object sender, DragEventArgs e)
{
switch (e.Data.GetData(DataFormats.Text).ToString())
{
case "labelSimpleObject":
_liner = new DrawningShip((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White);
break;
case "labelModifiedObject":
_liner = new DrawningLiner((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, Color.Black,
checkBoxSwimmingPool.Checked, checkBoxDopDeck.Checked);
break;
}
DrawLiner();
}
/// <summary>
/// Отправляем цвет с панели
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PanelColor_MouseDown(object sender, MouseEventArgs e)
{
(sender as Control).DoDragDrop((sender as Control).BackColor, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelBaseColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
/// <summary>
/// Принимаем основной цвет
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelBaseColor_DragDrop(object sender, DragEventArgs e)
{
if (_liner != null)
{
_liner.SetBaseColor((Color)e.Data.GetData(typeof(Color)));
DrawLiner();
}
}
/// <summary>
/// Принимаем дополнительный цвет
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelDopColor_DragDrop(object sender, DragEventArgs e)
{
if (_liner is DrawningLiner)
{
var liner = _liner as DrawningLiner;
liner.SetDopColor((Color)e.Data.GetData(typeof(Color)));
}
DrawLiner();
}
/// <summary>
/// Добавление машины
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonOk_Click(object sender, EventArgs e)
{
EventAddShip?.Invoke(_liner);
Close();
}
}
}

View File

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

View File

@@ -29,111 +29,112 @@
private void InitializeComponent()
{
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.groupBoxMaps = new System.Windows.Forms.GroupBox();
this.listBoxMaps = new System.Windows.Forms.ListBox();
this.buttonDeleteMap = new System.Windows.Forms.Button();
this.buttonAddMap = new System.Windows.Forms.Button();
this.textBoxNewMapName = new System.Windows.Forms.TextBox();
this.comboBoxSelectorMap = new System.Windows.Forms.ComboBox();
this.buttonDown = new System.Windows.Forms.Button();
this.ButtonAddShip = new System.Windows.Forms.Button();
this.buttonUp = new System.Windows.Forms.Button();
this.buttonRight = new System.Windows.Forms.Button();
this.buttonLeft = new System.Windows.Forms.Button();
this.ButtonShowStorage = new System.Windows.Forms.Button();
this.ButtonShowOnMap = new System.Windows.Forms.Button();
this.maskedTextBoxPosition = new System.Windows.Forms.MaskedTextBox();
this.comboBoxSelectorMap = new System.Windows.Forms.ComboBox();
this.ButtonRemoveShip = new System.Windows.Forms.Button();
this.ButtonAddShip = new System.Windows.Forms.Button();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.menuStrip = new System.Windows.Forms.MenuStrip();
this.файлToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.SaveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.LoadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.groupBox1.SuspendLayout();
this.groupBoxMaps.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.menuStrip.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.groupBoxMaps);
this.groupBox1.Controls.Add(this.buttonDown);
this.groupBox1.Controls.Add(this.ButtonAddShip);
this.groupBox1.Controls.Add(this.buttonUp);
this.groupBox1.Controls.Add(this.buttonRight);
this.groupBox1.Controls.Add(this.buttonLeft);
this.groupBox1.Controls.Add(this.ButtonShowStorage);
this.groupBox1.Controls.Add(this.ButtonShowOnMap);
this.groupBox1.Controls.Add(this.maskedTextBoxPosition);
this.groupBox1.Controls.Add(this.comboBoxSelectorMap);
this.groupBox1.Controls.Add(this.ButtonRemoveShip);
this.groupBox1.Controls.Add(this.ButtonAddShip);
this.groupBox1.Dock = System.Windows.Forms.DockStyle.Right;
this.groupBox1.Location = new System.Drawing.Point(600, 0);
this.groupBox1.Location = new System.Drawing.Point(677, 30);
this.groupBox1.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(200, 450);
this.groupBox1.Padding = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.groupBox1.Size = new System.Drawing.Size(229, 746);
this.groupBox1.TabIndex = 1;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Инструменты";
//
// buttonDown
// groupBoxMaps
//
this.buttonDown.BackgroundImage = global::WarmlyShip.Properties.Resources.Down;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonDown.Location = new System.Drawing.Point(96, 388);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(30, 30);
this.buttonDown.TabIndex = 11;
this.buttonDown.UseVisualStyleBackColor = true;
this.buttonDown.Click += new System.EventHandler(this.ButtonMove_Click);
this.groupBoxMaps.Controls.Add(this.listBoxMaps);
this.groupBoxMaps.Controls.Add(this.buttonDeleteMap);
this.groupBoxMaps.Controls.Add(this.buttonAddMap);
this.groupBoxMaps.Controls.Add(this.textBoxNewMapName);
this.groupBoxMaps.Controls.Add(this.comboBoxSelectorMap);
this.groupBoxMaps.Location = new System.Drawing.Point(7, 29);
this.groupBoxMaps.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.groupBoxMaps.Name = "groupBoxMaps";
this.groupBoxMaps.Padding = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.groupBoxMaps.Size = new System.Drawing.Size(215, 279);
this.groupBoxMaps.TabIndex = 12;
this.groupBoxMaps.TabStop = false;
this.groupBoxMaps.Text = "Карты";
//
// buttonUp
// listBoxMaps
//
this.buttonUp.BackgroundImage = global::WarmlyShip.Properties.Resources.Up;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonUp.Location = new System.Drawing.Point(96, 352);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(30, 30);
this.buttonUp.TabIndex = 10;
this.buttonUp.UseVisualStyleBackColor = true;
this.buttonUp.Click += new System.EventHandler(this.ButtonMove_Click);
this.listBoxMaps.FormattingEnabled = true;
this.listBoxMaps.ItemHeight = 20;
this.listBoxMaps.Location = new System.Drawing.Point(7, 145);
this.listBoxMaps.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.listBoxMaps.Name = "listBoxMaps";
this.listBoxMaps.Size = new System.Drawing.Size(201, 84);
this.listBoxMaps.TabIndex = 7;
this.listBoxMaps.SelectedIndexChanged += new System.EventHandler(this.ListBoxMaps_SelectedIndexChanged);
//
// buttonRight
// buttonDeleteMap
//
this.buttonRight.BackgroundImage = global::WarmlyShip.Properties.Resources.Right;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonRight.Location = new System.Drawing.Point(132, 388);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(30, 30);
this.buttonRight.TabIndex = 9;
this.buttonRight.UseVisualStyleBackColor = true;
this.buttonRight.Click += new System.EventHandler(this.ButtonMove_Click);
this.buttonDeleteMap.Location = new System.Drawing.Point(7, 240);
this.buttonDeleteMap.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonDeleteMap.Name = "buttonDeleteMap";
this.buttonDeleteMap.Size = new System.Drawing.Size(201, 31);
this.buttonDeleteMap.TabIndex = 6;
this.buttonDeleteMap.Text = "Удалить карту";
this.buttonDeleteMap.UseVisualStyleBackColor = true;
this.buttonDeleteMap.Click += new System.EventHandler(this.ButtonDeleteMap_Click);
//
// buttonLeft
// buttonAddMap
//
this.buttonLeft.BackgroundImage = global::WarmlyShip.Properties.Resources.Left;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonLeft.Location = new System.Drawing.Point(60, 388);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(30, 30);
this.buttonLeft.TabIndex = 8;
this.buttonLeft.UseVisualStyleBackColor = true;
this.buttonLeft.Click += new System.EventHandler(this.ButtonMove_Click);
this.buttonAddMap.Location = new System.Drawing.Point(7, 107);
this.buttonAddMap.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonAddMap.Name = "buttonAddMap";
this.buttonAddMap.Size = new System.Drawing.Size(201, 31);
this.buttonAddMap.TabIndex = 5;
this.buttonAddMap.Text = "Добавить карту";
this.buttonAddMap.UseVisualStyleBackColor = true;
this.buttonAddMap.Click += new System.EventHandler(this.ButtonAddMap_Click);
//
// ButtonShowStorage
// textBoxNewMapName
//
this.ButtonShowStorage.Location = new System.Drawing.Point(6, 193);
this.ButtonShowStorage.Name = "ButtonShowStorage";
this.ButtonShowStorage.Size = new System.Drawing.Size(182, 23);
this.ButtonShowStorage.TabIndex = 7;
this.ButtonShowStorage.Text = "Посмотреть хранилище";
this.ButtonShowStorage.UseVisualStyleBackColor = true;
this.ButtonShowStorage.Click += new System.EventHandler(this.ButtonShowStorage_Click);
//
// ButtonShowOnMap
//
this.ButtonShowOnMap.Location = new System.Drawing.Point(6, 243);
this.ButtonShowOnMap.Name = "ButtonShowOnMap";
this.ButtonShowOnMap.Size = new System.Drawing.Size(188, 23);
this.ButtonShowOnMap.TabIndex = 6;
this.ButtonShowOnMap.Text = "Посмотреть карту";
this.ButtonShowOnMap.UseVisualStyleBackColor = true;
this.ButtonShowOnMap.Click += new System.EventHandler(this.ButtonShowOnMap_Click);
//
// maskedTextBoxPosition
//
this.maskedTextBoxPosition.Location = new System.Drawing.Point(6, 108);
this.maskedTextBoxPosition.Mask = "00";
this.maskedTextBoxPosition.Name = "maskedTextBoxPosition";
this.maskedTextBoxPosition.Size = new System.Drawing.Size(188, 23);
this.maskedTextBoxPosition.TabIndex = 5;
this.textBoxNewMapName.Location = new System.Drawing.Point(7, 29);
this.textBoxNewMapName.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.textBoxNewMapName.Name = "textBoxNewMapName";
this.textBoxNewMapName.Size = new System.Drawing.Size(201, 27);
this.textBoxNewMapName.TabIndex = 0;
//
// comboBoxSelectorMap
//
@@ -141,54 +142,190 @@
this.comboBoxSelectorMap.Items.AddRange(new object[] {
"Простая карта",
"Море"});
this.comboBoxSelectorMap.Location = new System.Drawing.Point(6, 32);
this.comboBoxSelectorMap.Location = new System.Drawing.Point(7, 68);
this.comboBoxSelectorMap.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.comboBoxSelectorMap.Name = "comboBoxSelectorMap";
this.comboBoxSelectorMap.Size = new System.Drawing.Size(188, 23);
this.comboBoxSelectorMap.Size = new System.Drawing.Size(201, 28);
this.comboBoxSelectorMap.TabIndex = 4;
this.comboBoxSelectorMap.SelectedIndexChanged += new System.EventHandler(this.ComboBoxSelectorShip_SelectedIndexChanged);
//
// ButtonRemoveShip
// buttonDown
//
this.ButtonRemoveShip.Location = new System.Drawing.Point(6, 137);
this.ButtonRemoveShip.Name = "ButtonRemoveShip";
this.ButtonRemoveShip.Size = new System.Drawing.Size(188, 25);
this.ButtonRemoveShip.TabIndex = 3;
this.ButtonRemoveShip.Text = "Удалить корабль";
this.ButtonRemoveShip.UseVisualStyleBackColor = true;
this.ButtonRemoveShip.Click += new System.EventHandler(this.ButtonRemoveShip_Click);
this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDown.BackgroundImage = global::WarmlyShip.Properties.Resources.Down;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonDown.Location = new System.Drawing.Point(110, 685);
this.buttonDown.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(34, 40);
this.buttonDown.TabIndex = 11;
this.buttonDown.UseVisualStyleBackColor = true;
this.buttonDown.Click += new System.EventHandler(this.ButtonMove_Click);
//
// ButtonAddShip
//
this.ButtonAddShip.Location = new System.Drawing.Point(6, 61);
this.ButtonAddShip.Location = new System.Drawing.Point(14, 397);
this.ButtonAddShip.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.ButtonAddShip.Name = "ButtonAddShip";
this.ButtonAddShip.Size = new System.Drawing.Size(188, 25);
this.ButtonAddShip.Size = new System.Drawing.Size(201, 33);
this.ButtonAddShip.TabIndex = 2;
this.ButtonAddShip.Text = "Добавить корабль";
this.ButtonAddShip.UseVisualStyleBackColor = true;
this.ButtonAddShip.Click += new System.EventHandler(this.ButtonAddShip_Click);
//
// buttonUp
//
this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonUp.BackgroundImage = global::WarmlyShip.Properties.Resources.Up;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonUp.Location = new System.Drawing.Point(110, 637);
this.buttonUp.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(34, 40);
this.buttonUp.TabIndex = 10;
this.buttonUp.UseVisualStyleBackColor = true;
this.buttonUp.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonRight
//
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::WarmlyShip.Properties.Resources.Right;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonRight.Location = new System.Drawing.Point(151, 685);
this.buttonRight.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(34, 40);
this.buttonRight.TabIndex = 9;
this.buttonRight.UseVisualStyleBackColor = true;
this.buttonRight.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonLeft
//
this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonLeft.BackgroundImage = global::WarmlyShip.Properties.Resources.Left;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonLeft.Location = new System.Drawing.Point(69, 685);
this.buttonLeft.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(34, 40);
this.buttonLeft.TabIndex = 8;
this.buttonLeft.UseVisualStyleBackColor = true;
this.buttonLeft.Click += new System.EventHandler(this.ButtonMove_Click);
//
// ButtonShowStorage
//
this.ButtonShowStorage.Location = new System.Drawing.Point(14, 536);
this.ButtonShowStorage.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.ButtonShowStorage.Name = "ButtonShowStorage";
this.ButtonShowStorage.Size = new System.Drawing.Size(201, 31);
this.ButtonShowStorage.TabIndex = 7;
this.ButtonShowStorage.Text = "Посмотреть хранилище";
this.ButtonShowStorage.UseVisualStyleBackColor = true;
this.ButtonShowStorage.Click += new System.EventHandler(this.ButtonShowStorage_Click);
//
// ButtonShowOnMap
//
this.ButtonShowOnMap.Location = new System.Drawing.Point(14, 575);
this.ButtonShowOnMap.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.ButtonShowOnMap.Name = "ButtonShowOnMap";
this.ButtonShowOnMap.Size = new System.Drawing.Size(201, 31);
this.ButtonShowOnMap.TabIndex = 6;
this.ButtonShowOnMap.Text = "Посмотреть карту";
this.ButtonShowOnMap.UseVisualStyleBackColor = true;
this.ButtonShowOnMap.Click += new System.EventHandler(this.ButtonShowOnMap_Click);
//
// maskedTextBoxPosition
//
this.maskedTextBoxPosition.Location = new System.Drawing.Point(14, 439);
this.maskedTextBoxPosition.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.maskedTextBoxPosition.Mask = "00";
this.maskedTextBoxPosition.Name = "maskedTextBoxPosition";
this.maskedTextBoxPosition.Size = new System.Drawing.Size(201, 27);
this.maskedTextBoxPosition.TabIndex = 5;
//
// ButtonRemoveShip
//
this.ButtonRemoveShip.Location = new System.Drawing.Point(14, 477);
this.ButtonRemoveShip.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.ButtonRemoveShip.Name = "ButtonRemoveShip";
this.ButtonRemoveShip.Size = new System.Drawing.Size(201, 33);
this.ButtonRemoveShip.TabIndex = 3;
this.ButtonRemoveShip.Text = "Удалить корабль";
this.ButtonRemoveShip.UseVisualStyleBackColor = true;
this.ButtonRemoveShip.Click += new System.EventHandler(this.ButtonRemoveShip_Click);
//
// pictureBox1
//
this.pictureBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBox1.Location = new System.Drawing.Point(0, 0);
this.pictureBox1.Location = new System.Drawing.Point(0, 30);
this.pictureBox1.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(600, 450);
this.pictureBox1.Size = new System.Drawing.Size(677, 746);
this.pictureBox1.TabIndex = 0;
this.pictureBox1.TabStop = false;
//
// menuStrip
//
this.menuStrip.ImageScalingSize = new System.Drawing.Size(20, 20);
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.файлToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Padding = new System.Windows.Forms.Padding(7, 3, 0, 3);
this.menuStrip.Size = new System.Drawing.Size(906, 30);
this.menuStrip.TabIndex = 2;
//
// файлToolStripMenuItem
//
this.файлToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.SaveToolStripMenuItem,
this.LoadToolStripMenuItem});
this.файлToolStripMenuItem.Name = айлToolStripMenuItem";
this.файлToolStripMenuItem.Size = new System.Drawing.Size(59, 24);
this.файлToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(177, 26);
this.SaveToolStripMenuItem.Text = "Сохранение";
this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// LoadToolStripMenuItem
//
this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(177, 26);
this.LoadToolStripMenuItem.Text = "Загрузка";
this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
// openFileDialog
//
this.openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
this.saveFileDialog.Filter = "txt file | *.txt";
//
// FormMapWithSetWarmlyShip
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.ClientSize = new System.Drawing.Size(906, 776);
this.Controls.Add(this.pictureBox1);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.menuStrip);
this.MainMenuStrip = this.menuStrip;
this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.Name = "FormMapWithSetWarmlyShip";
this.Text = "FormMapWithSetWarmlyShip";
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBoxMaps.ResumeLayout(false);
this.groupBoxMaps.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
@@ -206,5 +343,16 @@
private Button buttonUp;
private Button buttonRight;
private Button buttonLeft;
private GroupBox groupBoxMaps;
private ListBox listBoxMaps;
private Button buttonDeleteMap;
private Button buttonAddMap;
private TextBox textBoxNewMapName;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
}
}

View File

@@ -8,51 +8,116 @@ using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.DataFormats;
using Serilog;
namespace WarmlyShip
{
public partial class FormMapWithSetWarmlyShip : Form
{
/// <summary>
/// Объект от класса карты с набором объектов
/// Словарь для выпадающего списка
/// </summary>
private MapWithSetWarmlyShipGeneric<DrawningObjectShip, AbstractMap> _mapWarmlyShipCollectionGeneric;
private readonly Dictionary<string, AbstractMap> _mapsDict = new()
{
{ "Простая карта", new SimpleMap() },
{ "Море", new MyMap() }
};
/// <summary>
/// Объект от коллекции карт
/// </summary>
private readonly MapsCollection _mapsCollection;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormMapWithSetWarmlyShip()
public FormMapWithSetWarmlyShip(ILogger logger)
{
InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBox1.Width, pictureBox1.Height);
comboBoxSelectorMap.Items.Clear();
foreach (var elem in _mapsDict)
{
comboBoxSelectorMap.Items.Add(elem.Key);
}
}
/// <summary>
/// Заполнение listBoxMaps
/// </summary>
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;
}
}
/// <summary>
/// Добавление карты
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddMap_Click(object sender, EventArgs e)
{
if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.Information($"Карта была не выбрана или не названа");
return;
}
if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text))
{
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.Information($"Нет карты с названием: {textBoxNewMapName.Text}");
return;
}
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps();
_logger.Information($"Добавлена карта {textBoxNewMapName.Text}");
}
/// <summary>
/// Выбор карты
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ComboBoxSelectorShip_SelectedIndexChanged(object sender, EventArgs e)
private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{
AbstractMap map = null;
switch (comboBoxSelectorMap.Text)
{
case "Простая карта":
map = new SimpleMap();
break;
case "Море":
map = new MyMap();
break;
}
if (map != null)
{
_mapWarmlyShipCollectionGeneric = new MapWithSetWarmlyShipGeneric<DrawningObjectShip, AbstractMap>(
pictureBox1.Width, pictureBox1.Height, map);
}
else
{
_mapWarmlyShipCollectionGeneric = null;
}
pictureBox1.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.Information($"Переход на карту с названием: {listBoxMaps.SelectedItem?.ToString() ?? string.Empty}");
}
/// <summary>
/// Удаление карты
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonDeleteMap_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
_logger.Information($"Удалена карту с названием: {listBoxMaps.SelectedItem?.ToString() ?? string.Empty}");
ReloadMaps();
}
}
/// <summary>
/// Добавление объекта
/// </summary>
@@ -60,27 +125,38 @@ namespace WarmlyShip
/// <param name="e"></param>
private void ButtonAddShip_Click(object sender, EventArgs e)
{
if (_mapWarmlyShipCollectionGeneric == null)
var formLinerConfig = new FormLinerConfig();
formLinerConfig.AddEvent(new(AddShip));
formLinerConfig.Show();
}
private void AddShip(DrawningShip liner)
{
try
{
return;
}
FormShip form = new();
if (form.ShowDialog() == DialogResult.OK)
{
DrawningObjectShip car = new(form.SelectedShip);
if ((_mapWarmlyShipCollectionGeneric + car) > -1)
if (listBoxMaps.SelectedIndex == -1)
{
MessageBox.Show("Перед добавлением объекта необходимо создать карту");
}
else if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectShip(liner) != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox1.Image = _mapWarmlyShipCollectionGeneric.ShowSet();
_logger.Information($"Добавлен объект");
pictureBox1.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
MessageBox.Show("Не удалось добавить объект");
_logger.Warning("Не удалось добавить объект");
}
}
catch(StorageOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
MessageBox.Show("Хранилище переполнено. Ошибка: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.Warning("Хранилище переполнено. Ошибка: {ex.Message}");
}
}
/// <summary>
/// Удаление объекта
/// </summary>
@@ -88,24 +164,43 @@ namespace WarmlyShip
/// <param name="e"></param>
private void ButtonRemoveShip_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("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if ((_mapWarmlyShipCollectionGeneric - pos) != null)
try
{
MessageBox.Show("Объект удален");
pictureBox1.Image = _mapWarmlyShipCollectionGeneric.ShowSet();
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
{
MessageBox.Show("Объект удален");
_logger.Information($"Из карты удален объект с позиции {pos}");
pictureBox1.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); ;
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.Warning($"Не удалось удалить объект с позиции {pos}");
}
}
else
catch (WarmlyShipNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show($"Ошибка удаления : {ex.Message}");
_logger.Warning($"Ошибка удаления : {ex.Message}");
}
catch (Exception ex)
{
MessageBox.Show($"Неизвестная ошибка : {ex.Message}");
_logger.Warning($"Неизвестная ошибка : {ex.Message}");
}
}
@@ -116,11 +211,11 @@ namespace WarmlyShip
/// <param name="e"></param>
private void ButtonShowStorage_Click(object sender, EventArgs e)
{
if (_mapWarmlyShipCollectionGeneric == null)
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
pictureBox1.Image = _mapWarmlyShipCollectionGeneric.ShowSet();
pictureBox1.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
/// <summary>
@@ -130,11 +225,11 @@ namespace WarmlyShip
/// <param name="e"></param>
private void ButtonShowOnMap_Click(object sender, EventArgs e)
{
if (_mapWarmlyShipCollectionGeneric == null)
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
pictureBox1.Image = _mapWarmlyShipCollectionGeneric.ShowOnMap();
pictureBox1.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowOnMap();
}
/// <summary>
@@ -144,7 +239,7 @@ namespace WarmlyShip
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_mapWarmlyShipCollectionGeneric == null)
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
@@ -167,9 +262,54 @@ namespace WarmlyShip
break;
}
pictureBox1.Image = _mapWarmlyShipCollectionGeneric.MoveObject(dir);
pictureBox1.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].MoveObject(dir);
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_mapsCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.Information($"Сохранение прошло успешно. Сохранено в {saveFileDialog.FileName}");
}
catch (Exception ex)
{
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.Warning($"Не удалось сохранить файл {saveFileDialog.FileName}. Ошибка: {ex.Message}");
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_mapsCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.Information($"Загрузка файла {openFileDialog.FileName} прошла успешно");
ReloadMaps();
}
catch (Exception ex)
{
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.Warning($"Не загрузился файл {openFileDialog.FileName}. Ошибка:{ex.Message}");
}
}
}
}
}

View File

@@ -57,4 +57,13 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>125, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>265, 17</value>
</metadata>
</root>

View File

@@ -9,7 +9,7 @@ namespace WarmlyShip
/// <summary>
/// Интерфейс для работы с объектом, прорисовываемым на форме
/// </summary>
internal interface IDrawningObject
internal interface IDrawningObject : IEquatable<IDrawningObject>
{
/// <summary>
/// Шаг перемещения объекта
@@ -39,5 +39,11 @@ namespace WarmlyShip
/// </summary>
/// <returns></returns>
(float Left, float Right, float Top, float Bottom) GetCurrentPosition();
/// <summary>
/// Получение информации по объекту
/// </summary>
/// <returns></returns>
string GetInfo();
}
}

View File

@@ -12,7 +12,7 @@ namespace WarmlyShip
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
internal class MapWithSetWarmlyShipGeneric<T, U>
where T : class, IDrawningObject
where T : class, IDrawningObject, IEnumerable<T>
where U : AbstractMap
{
/// <summary>
@@ -58,7 +58,7 @@ namespace WarmlyShip
/// Перегрузка оператора сложения
/// </summary>
/// <param name="map"></param>
/// <param name="car"></param>
/// <param name="ship"></param>
/// <returns></returns>
public static int operator +(MapWithSetWarmlyShipGeneric<T, U> map, T ship)
{
@@ -93,14 +93,11 @@ namespace WarmlyShip
public Bitmap ShowOnMap()
{
Shaking();
for (int i = 0; i < _setWarmlyShip.Count; i++)
foreach (var ship in _setWarmlyShip.GetShip())
{
var car = _setWarmlyShip.Get(i);
if (car != null)
{
return _map.CreateMap(_pictureWidth, _pictureHeight, car);
}
return _map.CreateMap(_pictureWidth, _pictureHeight, ship);
}
return new(_pictureWidth, _pictureHeight);
}
/// <summary>
@@ -116,6 +113,33 @@ namespace WarmlyShip
}
return new(_pictureWidth, _pictureHeight);
}
/// <summary>
/// Получение данных в виде строки
/// </summary>
/// <param name="sep"></param>
/// <returns></returns>
public string GetData(char separatorType, char separatorData)
{
string data = $"{_map.GetType().Name}{separatorType}";
foreach (var ship in _setWarmlyShip.GetShip())
{
data += $"{ship.GetInfo()}{separatorData}";
}
return data;
}
/// <summary>
/// Загрузка списка из массива строк
/// </summary>
/// <param name="records"></param>
public void LoadData(string[] records)
{
foreach (var rec in records)
{
_setWarmlyShip.Insert(DrawningObjectShip.Create(rec) as T);
}
}
/// <summary>
/// "Взбалтываем" набор, чтобы все элементы оказались в начале
/// </summary>
@@ -124,11 +148,11 @@ namespace WarmlyShip
int j = _setWarmlyShip.Count - 1;
for (int i = 0; i < _setWarmlyShip.Count; i++)
{
if (_setWarmlyShip.Get(i) == null)
if (_setWarmlyShip[i] == null)
{
for (; j > i; j--)
{
var car = _setWarmlyShip.Get(j);
var car = _setWarmlyShip[j];
if (car != null)
{
_setWarmlyShip.Insert(car, i);
@@ -167,23 +191,17 @@ namespace WarmlyShip
/// <param name="g"></param>
private void DrawWarmlyShip(Graphics g)
{
int i = 0;
int j = 0;
for (int k = 0; k < _setWarmlyShip.Count; k++)
int width = _pictureWidth / _placeSizeWidth;
int k = 0;
foreach (var ship in _setWarmlyShip.GetShip())
{
_setWarmlyShip.Get(k)?.SetObject(j + 10, i + 20, _pictureWidth, _pictureHeight);
_setWarmlyShip.Get(k)?.DrawningObject(g);
if (j >= _pictureWidth - 2 * _placeSizeWidth)
{
j = 0;
i += _placeSizeHeight;
}
else
{
j += _placeSizeWidth;
}
ship.SetObject(k % width * _placeSizeWidth + 10, k / width * _placeSizeHeight + 20, _pictureWidth, _pictureHeight);
ship.DrawningObject(g);
k++;
}
}
}
}

View File

@@ -0,0 +1,156 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip
{
/// <summary>
/// Класс для хранения коллекции карт
/// </summary>
internal class MapsCollection
{
/// <summary>
/// Словарь (хранилище) с картами
/// </summary>
readonly Dictionary<string, MapWithSetWarmlyShipGeneric<IDrawningObject, AbstractMap>> _mapStorages;
/// <summary>
/// Возвращение списка названий карт
/// </summary>
public List<string> Keys => _mapStorages.Keys.ToList();
/// <summary>
/// /// Ширина окна отрисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна отрисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Разделитель для записи информации по элементу словаря в файл
/// </summary>
private readonly char separatorDict = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char separatorData = ';';
/// <summary>
/// Конструктор
/// </summary>
/// <param name="pictureWidth"></param>
/// <param name="pictureHeight"></param>
public MapsCollection(int pictureWidth, int pictureHeight)
{
_mapStorages = new Dictionary<string, MapWithSetWarmlyShipGeneric<IDrawningObject, AbstractMap>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
/// <summary>
/// Добавление карты
/// </summary>
/// <param name="name">Название карты</param>
/// <param name="map">Карта</param>
public void AddMap(string name, AbstractMap map)
{
if (!Keys.Contains(name))
_mapStorages.Add(name, new MapWithSetWarmlyShipGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
}
/// <summary>
/// Удаление карты
/// </summary>
/// <param name="name">Название карты</param>
public void DelMap(string name)
{
if (Keys.Contains(name))
_mapStorages.Remove(name);
}
/// <summary>
/// Доступ к парковке
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public MapWithSetWarmlyShipGeneric<IDrawningObject, AbstractMap> this[string
ind]
{
get
{
if (Keys.Contains(ind))
return _mapStorages[ind];
return null;
}
}
/// <summary>
/// Метод записи информации в файл
/// </summary>
/// <param name="text">Строка, которую следует записать</param>
/// <param name="stream">Поток для записи</param>
private static void WriteToFile(string text, FileStream stream)
{
byte[] info = new UTF8Encoding(true).GetBytes(text);
stream.Write(info, 0, info.Length);
}
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns></returns>
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter sw = new(filename))
{
sw.Write($"MapsCollection{Environment.NewLine}");
foreach (var storage in _mapStorages)
{
sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}");
}
}
}
/// <summary>
/// Загрузка нформации по автомобилям на парковках из файла
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new Exception("Файл не найден");
}
using (StreamReader sr = new(filename))
{
if (!sr.ReadLine().Contains("MapsCollection"))
{
//если нет такой записи, то это не те данные
throw new Exception("Формат данных в файле не правильный");
}
//очищаем записи
_mapStorages.Clear();
while (!sr.EndOfStream)
{
var elem = sr.ReadLine().Split(separatorDict);
AbstractMap map = null;
switch (elem[1])
{
case "SimpleMap":
map = new SimpleMap();
break;
case "MyMap":
map = new MyMap();
break;
}
_mapStorages.Add(elem[0], new MapWithSetWarmlyShipGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
}
}
}
}
}

View File

@@ -1,3 +1,7 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
namespace WarmlyShip
{
internal static class Program
@@ -10,8 +14,26 @@ namespace WarmlyShip
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormMapWithSetWarmlyShip());
var services = new ServiceCollection();
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: "serilog.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
ApplicationConfiguration.Initialize();
Application.Run(new FormMapWithSetWarmlyShip(logger));
}
}
}
}

View File

@@ -11,23 +11,26 @@ namespace WarmlyShip
/// </summary>
/// <typeparam name="T"></typeparam>
internal class SetWarmlyShipGeneric<T>
where T : class
where T : class, IEnumerable<T>
{
/// <summary>
/// Массив объектов, которые храним
/// Список объектов, которые храним
/// </summary>
private readonly T[] _places;
private readonly List<T> _places;
/// <summary>
/// Количество объектов в массиве
/// Количество объектов в списке
/// </summary>
public int Count => _places.Length;
public int Count => _places.Count;
private readonly int _maxCount;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetWarmlyShipGeneric(int count)
{
_places = new T[count];
_maxCount = count;
_places = new List<T>();
}
/// <summary>
/// Добавление объекта в набор
@@ -36,16 +39,9 @@ namespace WarmlyShip
/// <returns></returns>
public int Insert(T ship)
{
if (ship == null)
{
return -1;
}
for (int i = Count - 1; i > 0; i--)
{
_places[i] = _places[i - 1];
}
_places[0] = ship;
return 0;
if (Count < _maxCount)
return Insert(ship, 0);
return -1;
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
@@ -55,26 +51,19 @@ namespace WarmlyShip
/// <returns></returns>
public int Insert(T ship, int position)
{
//TODO проверка на уникальность
if (Count >= _maxCount)
{
throw new StorageOverflowException(Count);
}
if (position < 0 || position > Count)
{
return -1;
}
int firstNullElementIndex = position;
while (_places[firstNullElementIndex] != null)
{
if (firstNullElementIndex >= Count)
{
return -1;
}
firstNullElementIndex++;
}
for (int i = firstNullElementIndex; i > position; i--)
{
_places[i] = _places[i - 1];
}
_places[position] = ship;
return 0;
_places.Insert(position, ship);
return position;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
@@ -83,26 +72,56 @@ namespace WarmlyShip
/// <returns></returns>
public T Remove(int position)
{
if (_places[position] == null)
{
if (position < 0 || position >= Count)
return null;
}
var result = _places[position];
_places[position] = null;
if (result == null)
{
throw new WarmlyShipNotFoundException(position);
}
_places.RemoveAt(position);
return result;
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T Get(int position)
public T this[int position]
{
if (_places[position] != null)
get
{
if (position < 0 || position >= Count)
return null;
return _places[position];
}
return null;
set
{
if (position < 0 || position >= _maxCount)
return;
_places.Add(value);
}
}
/// <summary>
/// Проход по набору до первого пустого
/// </summary>
/// <returns></returns>
public IEnumerable<T> GetShip()
{
foreach (var ship in _places)
{
if (ship != null)
{
yield return ship;
}
else
{
yield break;
}
}
}
}
}

View File

@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip
{
/// <summary>
/// Делегат для передачи объекта-автомобиля
/// </summary>
/// <param name="ship"></param>
public delegate void ShipDelegate(DrawningShip Ship);
}

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 WarmlyShip
{
[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

@@ -8,6 +8,39 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<None Remove="nlog.config" />
<None Remove="serilog.json" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</EmbeddedResource>
<EmbeddedResource Include="serilog.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="7.0.2" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyModel" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.2.1" />
<PackageReference Include="Serilog" Version="2.12.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="3.1.0" />
<PackageReference Include="Serilog.Settings.AppSettings" Version="2.2.2" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
<PackageReference Include="Serilog.Settings.Delegates" Version="1.0.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,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip
{
[Serializable]
internal class WarmlyShipNotFoundException : ApplicationException
{
public WarmlyShipNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
public WarmlyShipNotFoundException() : base() { }
public WarmlyShipNotFoundException(string message) : base(message) { }
public WarmlyShipNotFoundException(string message, Exception exception) : base(message, exception) { }
protected WarmlyShipNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true" internalLogLevel="Info">
<targets>
<target xsi:type="File" name="tofile" fileName="carlog-${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>

View File

@@ -0,0 +1,16 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/log.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}] {Level}: {Message};{NewLine}"
}
}
]
}
}