Compare commits

...

31 Commits

Author SHA1 Message Date
DozorovaA.A
ed2545c5d6 fix 2022-12-01 23:44:18 +04:00
DozorovaA.A
6f2ab026a9 add sort 2022-11-20 13:50:21 +04:00
DozorovaA.A
fdba620e54 comparison of object 2022-11-19 18:32:34 +04:00
DozorovaA.A
2b2b5f3e5e fix conflict 2022-11-16 15:51:02 +04:00
DozorovaA.A
6852b6bfb3 try fix conflict 2022-11-16 11:08:57 +04:00
DozorovaA.A
2fe71b1d22 little fix 2022-11-16 10:40:23 +04:00
DozorovaA.A
e6075c78d4 fix comment 2022-11-16 09:16:52 +04:00
DozorovaA.A
6be3584202 logging 2022-11-13 15:50:05 +04:00
DozorovaA.A
470476d1a8 add exceptions 2022-11-13 14:02:54 +04:00
DozorovaA.A
aa61b946f9 delete saved map 2022-11-13 13:45:08 +04:00
DozorovaA.A
0a889412fc fuull lab 2022-11-13 13:41:25 +04:00
820bf8c73b add comments 2022-11-02 11:05:18 +04:00
654a7f8ffd clear empty parametr of tank and change delegate 2022-10-30 10:59:29 +04:00
1370138f14 working create 2022-10-30 10:53:52 +04:00
bed31ce55e Add config form 2022-10-30 09:50:57 +04:00
533515c075 delete holes and return one masssage box 2022-10-19 09:10:35 +04:00
9848138396 little fix 2022-10-19 09:05:04 +04:00
e2129a1e01 Second Stage of lab work 2022-10-09 14:13:11 +04:00
878637552a Stage 2 of lab work 2022-10-09 13:40:22 +04:00
396b2d8f1e First stage of lab work 2022-10-09 13:17:48 +04:00
da0640612c fix and end work 2022-10-05 10:12:04 +04:00
42a7fe8911 fix comments 2022-09-24 17:12:16 +04:00
f6a15851ae changes forms 2022-09-21 21:31:10 +04:00
6cb049d4d6 generic classes 2022-09-21 20:59:18 +04:00
26955fb8c8 fix 2022-09-21 14:05:06 +04:00
bf9e8b5767 Add two map 2022-09-12 19:42:24 +04:00
f7b53c804c add check create 2022-09-12 19:23:19 +04:00
9120c6ecf9 Add check moving 2022-09-12 16:19:44 +04:00
55115cfb40 add interface 2022-09-11 18:05:41 +04:00
a6c1dd7c6f Create Tank 2022-09-11 18:00:27 +04:00
e81bd3dfa7 create constructor 2022-09-08 08:52:53 +04:00
35 changed files with 6615 additions and 35 deletions

View File

@ -0,0 +1,235 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ArmoredVehicle
{
internal abstract class AbstractMap:IEquatable<AbstractMap>
{
private IDrawningObject _drawningObject = null;
protected int[,] _map = null;
protected int _width;
protected int _height;
protected float _size_x;
protected float _size_y;
protected readonly Random _random = new();
protected readonly int _freeRoad = 0;
protected readonly int _barrier = 1;
public Bitmap CreateMap(int width, int height, IDrawningObject drawningObject)
{
_width = width;
_height = height;
_drawningObject = drawningObject;
GenerateMap();
while (!SetObjectOnMap())
{
GenerateMap();
}
return DrawMapWithObject();
}
public Bitmap MoveObject(Direction direction)
{
bool possibility = true;
(float XTop, float YTop, float XBottom, float YBottom) = _drawningObject.GetCurrentPosition();
bool busy = false;
int i;
int j;
int jt;
int i1;
switch (direction)
{
// вправо
case Direction.Right:
busy = false;
i = Math.Abs((int)Math.Ceiling(XBottom / _size_x));
j = Math.Abs((int)Math.Ceiling(YBottom / _size_y));
jt = Math.Abs((int)Math.Ceiling(YTop / _size_y));
i1 = Math.Abs((int)Math.Ceiling((XBottom + _drawningObject.Step)/ _size_x));
for (int r = i; r < i1; ++r)
{
for (int b = jt; b < j; ++b)
{
if (_map[r, b] == _barrier)
{
busy = true;
break;
}
}
if (busy)
{
break;
}
}
break;
//влево
case Direction.Left:
busy = false;
i = Math.Abs((int)Math.Ceiling((XTop - _drawningObject.Step )/ _size_x));
j = Math.Abs((int)Math.Ceiling(YBottom / _size_y));
jt = Math.Abs((int)Math.Ceiling(YTop / _size_y));
i1 = Math.Abs((int)Math.Ceiling((XTop)/ _size_x));
for (int r = i; r < i1; ++r)
{
for (int b = jt; b < j; ++b)
{
if (_map[r, b] == _barrier)
{
busy = true;
break;
}
}
if (busy)
{
break;
}
}
break;
//вверх
case Direction.Up:
{
busy = false;
i = Math.Abs((int)Math.Ceiling((XTop) / _size_x));
j = Math.Abs((int)((YTop)/ _size_y));
jt = Math.Abs((int)((YTop - _drawningObject.Step )/ _size_y));
i1 = Math.Abs((int)Math.Ceiling(XBottom / _size_x));
for (int r = i; r < i1; ++r)
{
for (int b = jt; b < j; ++b)
{
if (_map[r, b] == _barrier)
{
busy = true;
break;
}
}
if (busy)
{
break;
}
}
break;
}
//вниз
case Direction.Down:
{
busy = false;
i = (int)Math.Ceiling(XTop / _size_x);
j = (int)((YBottom + _drawningObject.Step) / _size_y);
jt = (int)(YBottom / _size_y);
i1 = (int)Math.Ceiling(XBottom / _size_x);
for (int r = i; r <= i1; r++)
{
for (int b = jt; b <= j; b++)
{
if (_map[r, b] == _barrier)
{
busy = true;
break;
}
}
if (busy)
{
break;
}
}
break;
}
}
if (busy)
{
possibility = false;
}
if (possibility)
{
_drawningObject.MoveObject(direction);
}
return DrawMapWithObject();
}
private bool SetObjectOnMap()
{
if (_drawningObject == null || _map == null)
{
return false;
}
(float XTop, float YTop, float XBottom, float YBottom) = _drawningObject.GetCurrentPosition();
int x = _random.Next(0, 10);
int y = _random.Next(0, 10);
int beginI = (int)(x / _size_x);
int endI = (int)(XBottom / _size_x);
int beginJ = (int)(y / _size_y);
int endJ = (int)(YBottom / _size_y);
for (int i = beginI; i <= endI; i++)
{
for(int j = beginJ; j <= endJ; j++)
{
if(_map[i, j] == _barrier)
{
return false;
}
}
}
_drawningObject.SetObject(x, y, _width, _height);
return true;
}
private Bitmap DrawMapWithObject()
{
Bitmap bmp = new(_width, _height);
if (_drawningObject == null || _map == null)
{
return bmp;
}
Graphics gr = Graphics.FromImage(bmp);
for (int i = 0; i < _map.GetLength(0); ++i)
{
for (int j = 0; j < _map.GetLength(1); ++j)
{
if (_map[i, j] == _freeRoad)
{
DrawRoadPart(gr, i, j);
}
else if (_map[i, j] == _barrier)
{
DrawBarrierPart(gr, i, j);
}
}
}
DrawRec(gr, 50, 50);
_drawningObject.DrawningObject(gr);
return bmp;
}
public void DrawRec(Graphics g, int countI, int couJj)
{
Pen p = new Pen(Color.Black);
for (int i = 0; i < countI; i++)
{
g.DrawLine(p, i * _size_x, 0, i * _size_x, 1000);
g.DrawLine(p, 0, i * _size_y, 1000, i * _size_y);
}
}
protected abstract void GenerateMap();
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)
{
return this == other && this._width == other._width &&
this._height == other._height && this._map == other._map && this._drawningObject == other._drawningObject;
}
}
}

View File

@ -8,4 +8,43 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<None Remove="nlog.config" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="nlog.config">
<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.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" 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="Serilog.Extensions.Logging" Version="3.1.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
</Project>

View File

@ -6,8 +6,18 @@ using System.Threading.Tasks;
namespace ArmoredVehicle
{
internal class ArmoredVehicleEntity
public class ArmoredVehicleEntity
{
public ArmoredVehicleEntity(int speed, float weight, Color bodyColor)
{
Random rnd = new();
Speed = speed <= 0 ? rnd.Next(50, 150) : speed;
Weight = weight <= 0 ? rnd.Next(40, 70) : weight;
BodyColor = bodyColor;
}
/// <summary>
/// Скорость
/// </summary>
@ -31,12 +41,6 @@ namespace ArmoredVehicle
/// <param name="weight"></param>
/// <param name="bodyColor"></param>
/// <returns></returns>
public void Init(int speed, float weight, Color bodyColor)
{
Random rnd = new();
Speed = speed <= 0 ? rnd.Next(50, 150) : speed;
Weight = weight <= 0 ? rnd.Next(40, 70) : weight;
BodyColor = bodyColor;
}
}
}

View File

@ -9,8 +9,9 @@ namespace ArmoredVehicle
/// <summary>
/// Направление перемещения
/// </summary>
internal enum Direction
public enum Direction
{
None = 0,
Up = 1,
Down = 2,
Left = 3,

View File

@ -6,20 +6,20 @@ using System.Threading.Tasks;
namespace ArmoredVehicle
{
internal class DrawingArmoredVehicle
public class DrawingArmoredVehicle
{
/// <summary>
/// Класс-сущность
/// </summary>
public ArmoredVehicleEntity ArmoredVehicle { get; private set; }
public ArmoredVehicleEntity ArmoredVehicle { get; protected set; }
/// <summary>
/// Левая координата отрисовки
/// </summary>
private float _startPosX;
protected float _startPosX;
/// <summary>
/// Верхняя кооридната отрисовки
/// </summary>
private float _startPosY;
protected float _startPosY;
/// <summary>
/// Ширина окна отрисовки
/// </summary>
@ -31,22 +31,34 @@ namespace ArmoredVehicle
/// <summary>
/// Ширина отрисовки
/// </summary>
private readonly int _ArmoredVehicleWidth = 210;
private readonly int _ArmoredVehicleWidth = 200;
/// <summary>
/// Высота отрисовки
/// </summary>
private readonly int _ArmoredVehicleHeight = 50;
private readonly int _ArmoredVehicleHeight = 60;
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес </param>
/// <param name="bodyColor">Цвет</param>
public void Init(int speed, float weight, Color bodyColor)
public DrawingArmoredVehicle(int speed, float weight, Color bodyColor)
{
ArmoredVehicle = new ArmoredVehicleEntity();
ArmoredVehicle.Init(speed, weight, bodyColor);
ArmoredVehicle = new ArmoredVehicleEntity(speed, weight, bodyColor);
}
public DrawingArmoredVehicle(int speed, float weight, Color bodyColor, int ArmoredVehicleWidth, int ArmoredVehicleHeight)
:this(speed, weight, bodyColor)
{
_ArmoredVehicleHeight = ArmoredVehicleHeight + 50;
_ArmoredVehicleWidth = ArmoredVehicleWidth + 150;
}
public DrawingArmoredVehicle Copy(int? speed = null, float? weight = null, Color? bodyColor = null)
{
return new DrawingArmoredVehicle(speed ?? ArmoredVehicle.Speed, weight ?? ArmoredVehicle.Weight, bodyColor ?? ArmoredVehicle.BodyColor);
}
/// <summary>
/// Установка позиции
/// </summary>
@ -129,7 +141,7 @@ namespace ArmoredVehicle
/// Отрисовка
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
public virtual void DrawTransport(Graphics g)
{
if (_startPosX < 0 || _startPosY < 0
|| !_pictureHeight.HasValue || !_pictureWidth.HasValue)
@ -155,9 +167,6 @@ namespace ArmoredVehicle
g.DrawRectangle(pen, _startPosX + 15, _startPosY+20, 200, 20);
g.DrawEllipse(pen, _startPosX + 15, _startPosY + 25, 200, 35);
}
/// <summary>
/// Смена границ формы отрисовки
@ -183,5 +192,13 @@ namespace ArmoredVehicle
_startPosY = _pictureHeight.Value - _ArmoredVehicleHeight;
}
}
/// <summary>
/// Получение текущей позиции объекта
/// </summary>
/// <returns></returns>
public (float Left, float Right, float Top, float Bottom) GetCurrentPosition()
{
return (_startPosX + 15, _startPosY, _startPosX + 15 + _ArmoredVehicleWidth, _startPosY + _ArmoredVehicleHeight);
}
}
}

View File

@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ArmoredVehicle
{
internal class DrawingTank : DrawingArmoredVehicle
{
public DrawingTank(int speed, float weight, Color bodyColor, Color dopColor, bool machineGun, bool tower)
: base(speed, weight, bodyColor, 200, 60)
{
ArmoredVehicle = new TankEnity(speed, weight, bodyColor, dopColor, machineGun, tower);
}
public DrawingTank Copy(int? speed = null, float? weight = null, Color? bodyColor = null,
Color? dopColor = null, bool? machineGun = null, bool? tower = null)
{
var e = (TankEnity)ArmoredVehicle;
return new DrawingTank(speed ?? e.Speed, weight ?? e.Weight, bodyColor ?? e.BodyColor, dopColor ?? e.DopColor,
machineGun ?? e.MachineGun, tower ?? e.Tower);
}
public override void DrawTransport(Graphics g)
{
if (ArmoredVehicle is not TankEnity machine)
{
return;
}
Brush br = new SolidBrush(machine?.DopColor ?? Color.Black);
Pen p = new Pen(machine?.DopColor ?? Color.Black, 5);
_startPosY += 40;
base.DrawTransport(g);
_startPosY -= 40;
if (machine.Tower)
{
g.FillRectangle(br, _startPosX + 60, _startPosY + 10, 80, 30);
g.DrawLine(p, _startPosX + 90, _startPosY +20, _startPosX + 250, _startPosY + 20);
if (machine.MachineGun)
{
p = new Pen(machine?.DopColor ?? Color.Black, 3);
g.DrawLine(p, _startPosX + 90, _startPosY, _startPosX + 90, _startPosY + 10);
g.DrawLine(p, _startPosX + 85, _startPosY + 5, _startPosX + 120, _startPosY + 5);
}
}
}
}
}

View File

@ -0,0 +1,81 @@
namespace ArmoredVehicle
{
internal class DrawningObject : IDrawningObject
{
private DrawingArmoredVehicle _machine = null;
public DrawningObject(DrawingArmoredVehicle machine)
{
_machine = machine;
}
public DrawingArmoredVehicle GetMachine => _machine;
public float Step => _machine?.ArmoredVehicle?.Step ?? 0;
public (float Left, float Right, float Top, float Bottom) GetCurrentPosition()
{
return _machine?.GetCurrentPosition() ?? default;
}
public void MoveObject(Direction direction)
{
_machine?.MoveTransport(direction);
}
public void SetObject(int x, int y, int width, int height)
{
_machine.SetPosition(x, y, width, height);
}
void IDrawningObject.DrawningObject(Graphics g)
{
_machine.DrawTransport(g);
}
public string GetInfo() => _machine?.GetDataForSave();
public static IDrawningObject Create(string data) => new DrawningObject(data.CreateDrawningCar());
public bool Equals(IDrawningObject? other)
{
if (other == null)
{
return false;
}
var otheMachine = other as DrawningObject;
if (otheMachine == null)
{
return false;
}
var machine = _machine.ArmoredVehicle;
var otherMachineMachine = otheMachine._machine.ArmoredVehicle;
if (machine.Speed != otherMachineMachine.Speed)
{
return false;
}
if (machine.Weight != otherMachineMachine.Weight)
{
return false;
}
if (machine.BodyColor != otherMachineMachine.BodyColor)
{
return false;
}
if (machine is TankEnity && otherMachineMachine is TankEnity)
{
var tank = machine as TankEnity;
var otherMachineTank = otherMachineMachine as TankEnity;
if (tank.DopColor != otherMachineTank.DopColor || tank.Tower != otherMachineTank.Tower ||
tank.MachineGun != otherMachineTank.MachineGun)
{
return false;
}
}else if (machine is TankEnity || otherMachineMachine is TankEnity)
{
return false;
}
return true;
}
}
}

View File

@ -0,0 +1,53 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ArmoredVehicle
{
internal static class ExtentionMachine
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public static DrawingArmoredVehicle CreateDrawningCar(this string info)
{
string[] strs = info.Split(_separatorForObject);
if (strs.Length == 3)
{
return new DrawingArmoredVehicle(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]));
}
if (strs.Length == 6)
{
return new DrawingTank(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="drawningMachine"></param>
/// <returns></returns>
public static string GetDataForSave(this DrawingArmoredVehicle drawningMachine)
{
var car = drawningMachine.ArmoredVehicle;
var str = $"{car.Speed}{_separatorForObject}{car.Weight}{_separatorForObject}{car.BodyColor.Name}";
if (car is not TankEnity tank)
{
return str;
}
return $"{str}{_separatorForObject}{tank.DopColor.Name}{_separatorForObject}{tank.MachineGun}{_separatorForObject}{tank.Tower}";
}
}
}

View File

@ -0,0 +1,389 @@
namespace ArmoredVehicle
{
partial class FormMachineConfig
{
/// <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.labelHard = new System.Windows.Forms.Label();
this.labelSimple = new System.Windows.Forms.Label();
this.checkBoxMachineGun = new System.Windows.Forms.CheckBox();
this.checkBoxTower = new System.Windows.Forms.CheckBox();
this.numericUpDownWeight = new System.Windows.Forms.NumericUpDown();
this.numericUpDownSpeed = new System.Windows.Forms.NumericUpDown();
this.labelWeight = new System.Windows.Forms.Label();
this.labelSpeed = new System.Windows.Forms.Label();
this.groupBoxColors = new System.Windows.Forms.GroupBox();
this.panelPale = new System.Windows.Forms.Panel();
this.panelOrange = new System.Windows.Forms.Panel();
this.panelLightGreen = 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.panelIndigo = new System.Windows.Forms.Panel();
this.panelCoral = new System.Windows.Forms.Panel();
this.panelObject = new System.Windows.Forms.Panel();
this.labelDopColor = new System.Windows.Forms.Label();
this.labelColor = 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();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).BeginInit();
this.groupBoxColors.SuspendLayout();
this.panelObject.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).BeginInit();
this.SuspendLayout();
//
// groupBoxConfig
//
this.groupBoxConfig.Controls.Add(this.labelHard);
this.groupBoxConfig.Controls.Add(this.labelSimple);
this.groupBoxConfig.Controls.Add(this.checkBoxMachineGun);
this.groupBoxConfig.Controls.Add(this.checkBoxTower);
this.groupBoxConfig.Controls.Add(this.numericUpDownWeight);
this.groupBoxConfig.Controls.Add(this.numericUpDownSpeed);
this.groupBoxConfig.Controls.Add(this.labelWeight);
this.groupBoxConfig.Controls.Add(this.labelSpeed);
this.groupBoxConfig.Controls.Add(this.groupBoxColors);
this.groupBoxConfig.Location = new System.Drawing.Point(8, 14);
this.groupBoxConfig.Name = "groupBoxConfig";
this.groupBoxConfig.Size = new System.Drawing.Size(667, 440);
this.groupBoxConfig.TabIndex = 0;
this.groupBoxConfig.TabStop = false;
this.groupBoxConfig.Text = "Параметры";
//
// labelHard
//
this.labelHard.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelHard.Location = new System.Drawing.Point(507, 318);
this.labelHard.Name = "labelHard";
this.labelHard.Size = new System.Drawing.Size(134, 38);
this.labelHard.TabIndex = 9;
this.labelHard.Text = "Продвинутый";
this.labelHard.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelHard.MouseDown += new System.Windows.Forms.MouseEventHandler(this.labelObject_MouseDown);
//
// labelSimple
//
this.labelSimple.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelSimple.Location = new System.Drawing.Point(292, 318);
this.labelSimple.Name = "labelSimple";
this.labelSimple.Size = new System.Drawing.Size(121, 38);
this.labelSimple.TabIndex = 8;
this.labelSimple.Text = "Простой";
this.labelSimple.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelSimple.MouseDown += new System.Windows.Forms.MouseEventHandler(this.labelObject_MouseDown);
//
// checkBoxMachineGun
//
this.checkBoxMachineGun.AutoSize = true;
this.checkBoxMachineGun.Location = new System.Drawing.Point(5, 235);
this.checkBoxMachineGun.Name = "checkBoxMachineGun";
this.checkBoxMachineGun.Size = new System.Drawing.Size(260, 29);
this.checkBoxMachineGun.TabIndex = 6;
this.checkBoxMachineGun.Text = "Признак наличия пулемета";
this.checkBoxMachineGun.UseVisualStyleBackColor = true;
//
// checkBoxTower
//
this.checkBoxTower.AutoSize = true;
this.checkBoxTower.Location = new System.Drawing.Point(5, 202);
this.checkBoxTower.Name = "checkBoxTower";
this.checkBoxTower.Size = new System.Drawing.Size(238, 29);
this.checkBoxTower.TabIndex = 5;
this.checkBoxTower.Text = "Признак наличия башни";
this.checkBoxTower.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
this.numericUpDownWeight.Location = new System.Drawing.Point(96, 135);
this.numericUpDownWeight.Maximum = new decimal(new int[] {
100000,
0,
0,
0});
this.numericUpDownWeight.Minimum = new decimal(new int[] {
100,
0,
0,
0});
this.numericUpDownWeight.Name = "numericUpDownWeight";
this.numericUpDownWeight.Size = new System.Drawing.Size(106, 31);
this.numericUpDownWeight.TabIndex = 4;
this.numericUpDownWeight.Value = new decimal(new int[] {
100,
0,
0,
0});
//
// numericUpDownSpeed
//
this.numericUpDownSpeed.Location = new System.Drawing.Point(97, 94);
this.numericUpDownSpeed.Maximum = new decimal(new int[] {
100000,
0,
0,
0});
this.numericUpDownSpeed.Minimum = new decimal(new int[] {
100,
0,
0,
0});
this.numericUpDownSpeed.Name = "numericUpDownSpeed";
this.numericUpDownSpeed.Size = new System.Drawing.Size(105, 31);
this.numericUpDownSpeed.TabIndex = 3;
this.numericUpDownSpeed.Value = new decimal(new int[] {
100,
0,
0,
0});
//
// labelWeight
//
this.labelWeight.AutoSize = true;
this.labelWeight.Location = new System.Drawing.Point(6, 134);
this.labelWeight.Name = "labelWeight";
this.labelWeight.Size = new System.Drawing.Size(39, 25);
this.labelWeight.TabIndex = 2;
this.labelWeight.Text = "Вес";
//
// labelSpeed
//
this.labelSpeed.AutoSize = true;
this.labelSpeed.Location = new System.Drawing.Point(6, 91);
this.labelSpeed.Name = "labelSpeed";
this.labelSpeed.Size = new System.Drawing.Size(89, 25);
this.labelSpeed.TabIndex = 1;
this.labelSpeed.Text = "Скорость";
//
// groupBoxColors
//
this.groupBoxColors.Controls.Add(this.panelPale);
this.groupBoxColors.Controls.Add(this.panelOrange);
this.groupBoxColors.Controls.Add(this.panelLightGreen);
this.groupBoxColors.Controls.Add(this.panelGreen);
this.groupBoxColors.Controls.Add(this.panelBlue);
this.groupBoxColors.Controls.Add(this.panelRed);
this.groupBoxColors.Controls.Add(this.panelIndigo);
this.groupBoxColors.Controls.Add(this.panelCoral);
this.groupBoxColors.Location = new System.Drawing.Point(292, 91);
this.groupBoxColors.Name = "groupBoxColors";
this.groupBoxColors.Size = new System.Drawing.Size(349, 205);
this.groupBoxColors.TabIndex = 0;
this.groupBoxColors.TabStop = false;
this.groupBoxColors.Text = "Цвета";
//
// panelPale
//
this.panelPale.BackColor = System.Drawing.Color.PaleTurquoise;
this.panelPale.Location = new System.Drawing.Point(183, 111);
this.panelPale.Name = "panelPale";
this.panelPale.Size = new System.Drawing.Size(64, 57);
this.panelPale.TabIndex = 1;
this.panelPale.MouseDown += new System.Windows.Forms.MouseEventHandler(this.panelColor_MouseDown);
//
// panelOrange
//
this.panelOrange.BackColor = System.Drawing.Color.Orange;
this.panelOrange.Location = new System.Drawing.Point(101, 111);
this.panelOrange.Name = "panelOrange";
this.panelOrange.Size = new System.Drawing.Size(64, 57);
this.panelOrange.TabIndex = 1;
this.panelOrange.MouseDown += new System.Windows.Forms.MouseEventHandler(this.panelColor_MouseDown);
//
// panelLightGreen
//
this.panelLightGreen.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(255)))), ((int)(((byte)(128)))));
this.panelLightGreen.Location = new System.Drawing.Point(19, 111);
this.panelLightGreen.Name = "panelLightGreen";
this.panelLightGreen.Size = new System.Drawing.Size(64, 57);
this.panelLightGreen.TabIndex = 1;
this.panelLightGreen.MouseDown += new System.Windows.Forms.MouseEventHandler(this.panelColor_MouseDown);
//
// panelGreen
//
this.panelGreen.BackColor = System.Drawing.Color.Green;
this.panelGreen.Location = new System.Drawing.Point(262, 31);
this.panelGreen.Name = "panelGreen";
this.panelGreen.Size = new System.Drawing.Size(64, 57);
this.panelGreen.TabIndex = 1;
this.panelGreen.MouseDown += new System.Windows.Forms.MouseEventHandler(this.panelColor_MouseDown);
//
// panelBlue
//
this.panelBlue.BackColor = System.Drawing.Color.Blue;
this.panelBlue.Location = new System.Drawing.Point(183, 30);
this.panelBlue.Name = "panelBlue";
this.panelBlue.Size = new System.Drawing.Size(64, 57);
this.panelBlue.TabIndex = 1;
this.panelBlue.MouseDown += new System.Windows.Forms.MouseEventHandler(this.panelColor_MouseDown);
//
// panelRed
//
this.panelRed.BackColor = System.Drawing.Color.Red;
this.panelRed.Location = new System.Drawing.Point(101, 31);
this.panelRed.Name = "panelRed";
this.panelRed.Size = new System.Drawing.Size(64, 57);
this.panelRed.TabIndex = 1;
this.panelRed.MouseDown += new System.Windows.Forms.MouseEventHandler(this.panelColor_MouseDown);
//
// panelIndigo
//
this.panelIndigo.BackColor = System.Drawing.Color.Indigo;
this.panelIndigo.Location = new System.Drawing.Point(262, 111);
this.panelIndigo.Name = "panelIndigo";
this.panelIndigo.Size = new System.Drawing.Size(64, 57);
this.panelIndigo.TabIndex = 1;
this.panelIndigo.MouseDown += new System.Windows.Forms.MouseEventHandler(this.panelColor_MouseDown);
//
// panelCoral
//
this.panelCoral.BackColor = System.Drawing.Color.Coral;
this.panelCoral.Location = new System.Drawing.Point(19, 31);
this.panelCoral.Name = "panelCoral";
this.panelCoral.Size = new System.Drawing.Size(64, 57);
this.panelCoral.TabIndex = 0;
this.panelCoral.MouseDown += new System.Windows.Forms.MouseEventHandler(this.panelColor_MouseDown);
//
// panelObject
//
this.panelObject.AllowDrop = true;
this.panelObject.Controls.Add(this.labelDopColor);
this.panelObject.Controls.Add(this.labelColor);
this.panelObject.Controls.Add(this.pictureBoxObject);
this.panelObject.Location = new System.Drawing.Point(695, 27);
this.panelObject.Name = "panelObject";
this.panelObject.Size = new System.Drawing.Size(475, 399);
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(303, 14);
this.labelDopColor.Name = "labelDopColor";
this.labelDopColor.Size = new System.Drawing.Size(121, 38);
this.labelDopColor.TabIndex = 10;
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.labelDopColor_DragEnter);
//
// labelColor
//
this.labelColor.AllowDrop = true;
this.labelColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelColor.Location = new System.Drawing.Point(78, 14);
this.labelColor.Name = "labelColor";
this.labelColor.Size = new System.Drawing.Size(121, 38);
this.labelColor.TabIndex = 9;
this.labelColor.Text = "Цвет";
this.labelColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.labelColor_DragDrop);
this.labelColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.labelColor_DragEnter);
//
// pictureBoxObject
//
this.pictureBoxObject.Location = new System.Drawing.Point(17, 59);
this.pictureBoxObject.Name = "pictureBoxObject";
this.pictureBoxObject.Size = new System.Drawing.Size(441, 321);
this.pictureBoxObject.TabIndex = 0;
this.pictureBoxObject.TabStop = false;
//
// buttonAdd
//
this.buttonAdd.Location = new System.Drawing.Point(695, 432);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(138, 34);
this.buttonAdd.TabIndex = 2;
this.buttonAdd.Text = "Добавить";
this.buttonAdd.UseVisualStyleBackColor = true;
this.buttonAdd.Click += new System.EventHandler(this.buttonAdd_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(862, 433);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(133, 34);
this.buttonCancel.TabIndex = 3;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
//
// FormMachineConfig
//
this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1182, 478);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonAdd);
this.Controls.Add(this.panelObject);
this.Controls.Add(this.groupBoxConfig);
this.Name = "FormMachineConfig";
this.Text = "Создание объектов";
this.groupBoxConfig.ResumeLayout(false);
this.groupBoxConfig.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).EndInit();
this.groupBoxColors.ResumeLayout(false);
this.panelObject.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).EndInit();
this.ResumeLayout(false);
}
#endregion
private GroupBox groupBoxConfig;
private Label labelWeight;
private Label labelSpeed;
private GroupBox groupBoxColors;
private NumericUpDown numericUpDownWeight;
private NumericUpDown numericUpDownSpeed;
private CheckBox checkBoxMachineGun;
private CheckBox checkBoxTower;
private Label labelHard;
private Label labelSimple;
private Panel panelPale;
private Panel panelOrange;
private Panel panelLightGreen;
private Panel panelGreen;
private Panel panelBlue;
private Panel panelRed;
private Panel panelIndigo;
private Panel panelCoral;
private Panel panelObject;
private Label labelDopColor;
private Label labelColor;
private PictureBox pictureBoxObject;
private Button buttonAdd;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,204 @@
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 ArmoredVehicle
{
public partial class FormMachineConfig : Form
{
/// <summary>
/// Переменная-выбранная машина
/// </summary>
DrawingArmoredVehicle _machine = null;
/// <summary>
/// Событие
/// </summary>
public event Action<DrawingArmoredVehicle> EventAddMachine;
/// <summary>
/// Конструктор
/// </summary>
public FormMachineConfig()
{
InitializeComponent();
panelCoral.MouseDown += panelColor_MouseDown;
panelRed.MouseDown += panelColor_MouseDown;
panelBlue.MouseDown += panelColor_MouseDown;
panelOrange.MouseDown += panelColor_MouseDown;
panelPale.MouseDown += panelColor_MouseDown;
panelGreen.MouseDown += panelColor_MouseDown;
panelIndigo.MouseDown += panelColor_MouseDown;
panelLightGreen.MouseDown += panelColor_MouseDown;
buttonCancel.Click += (s, e) => Close();
}
/// <summary>
/// Отрисовать машину
/// </summary>
private void DrawMachine()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_machine?.SetPosition(5, 5, pictureBoxObject.Width,
pictureBoxObject.Height);
_machine?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
/// <summary>
/// Добавление события
/// </summary>
/// <param name="ev"></param>
public void AddEvent(Action<DrawingArmoredVehicle> ev)
{
if(EventAddMachine == null)
{
EventAddMachine = new (ev);
}
else
{
EventAddMachine += ev;
}
}
/// <summary>
/// Передаем информацию при нажатии на Label
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void labelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label).DoDragDrop((sender as Label).Name, DragDropEffects.Move | DragDropEffects.Copy);
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void panelObject_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text))
{
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 "labelSimple":
_machine = new DrawingArmoredVehicle((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White);
break;
case "labelHard":
_machine = new DrawingTank((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, Color.Black,
checkBoxMachineGun.Checked, checkBoxTower.Checked);
break;
}
DrawMachine();
}
/// <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 labelColor_DragDrop(object sender, DragEventArgs e)
{
var color = (Color)e.Data.GetData(typeof(Color));
if (_machine is DrawingTank)
{
_machine = ((DrawingTank)_machine).Copy(bodyColor: color);
}
else if (_machine is DrawingArmoredVehicle)
{
_machine = _machine.Copy(bodyColor: color);
}
DrawMachine();
}
/// <summary>
/// Проверка получаемой информации (ее типа на соответствие требуемому)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void labelColor_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 labelDopColor_DragEnter(object sender, DragEventArgs e)
{
if(_machine is DrawingTank)
{
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 labelDopColor_DragDrop(object sender, DragEventArgs e)
{
var color = (Color)e.Data.GetData(typeof(Color));
var machine = _machine as DrawingTank;
if (machine != null)
{
_machine = machine.Copy(dopColor: color);
}
DrawMachine();
}
/// <summary>
/// Добавление машины
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAdd_Click(object sender, EventArgs e)
{
EventAddMachine?.Invoke(_machine);
Close();
}
}
}

View File

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

View File

@ -0,0 +1,370 @@
namespace ArmoredVehicle
{
partial class FormMapWithSetMachine
{
/// <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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormMapWithSetMachine));
this.groupBoxInstruments = new System.Windows.Forms.GroupBox();
this.groupBoxMap = 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.comboBoxSelectorMap = new System.Windows.Forms.ComboBox();
this.textBoxNewMapName = new System.Windows.Forms.TextBox();
this.maskedTextBoxPosition = new System.Windows.Forms.MaskedTextBox();
this.ButtonDown = new System.Windows.Forms.Button();
this.ButtonRight = new System.Windows.Forms.Button();
this.ButtonLeft = new System.Windows.Forms.Button();
this.ButtonUp = new System.Windows.Forms.Button();
this.buttonMap = new System.Windows.Forms.Button();
this.buttonStore = new System.Windows.Forms.Button();
this.buttonDelete = new System.Windows.Forms.Button();
this.buttonAdd = new System.Windows.Forms.Button();
this.pictureBoxImage = 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.SortBuTypeButton = new System.Windows.Forms.Button();
this.SortByColorButton = new System.Windows.Forms.Button();
this.groupBoxInstruments.SuspendLayout();
this.groupBoxMap.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxImage)).BeginInit();
this.menuStrip.SuspendLayout();
this.SuspendLayout();
//
// groupBoxInstruments
//
this.groupBoxInstruments.Controls.Add(this.SortByColorButton);
this.groupBoxInstruments.Controls.Add(this.SortBuTypeButton);
this.groupBoxInstruments.Controls.Add(this.groupBoxMap);
this.groupBoxInstruments.Controls.Add(this.maskedTextBoxPosition);
this.groupBoxInstruments.Controls.Add(this.ButtonDown);
this.groupBoxInstruments.Controls.Add(this.ButtonRight);
this.groupBoxInstruments.Controls.Add(this.ButtonLeft);
this.groupBoxInstruments.Controls.Add(this.ButtonUp);
this.groupBoxInstruments.Controls.Add(this.buttonMap);
this.groupBoxInstruments.Controls.Add(this.buttonStore);
this.groupBoxInstruments.Controls.Add(this.buttonDelete);
this.groupBoxInstruments.Controls.Add(this.buttonAdd);
this.groupBoxInstruments.Dock = System.Windows.Forms.DockStyle.Right;
this.groupBoxInstruments.Location = new System.Drawing.Point(964, 33);
this.groupBoxInstruments.Name = "groupBoxInstruments";
this.groupBoxInstruments.Size = new System.Drawing.Size(300, 1003);
this.groupBoxInstruments.TabIndex = 0;
this.groupBoxInstruments.TabStop = false;
this.groupBoxInstruments.Text = "Инструменты";
//
// groupBoxMap
//
this.groupBoxMap.Controls.Add(this.buttonDeleteMap);
this.groupBoxMap.Controls.Add(this.listBoxMaps);
this.groupBoxMap.Controls.Add(this.buttonAddMap);
this.groupBoxMap.Controls.Add(this.comboBoxSelectorMap);
this.groupBoxMap.Controls.Add(this.textBoxNewMapName);
this.groupBoxMap.Location = new System.Drawing.Point(13, 30);
this.groupBoxMap.Name = "groupBoxMap";
this.groupBoxMap.Size = new System.Drawing.Size(267, 408);
this.groupBoxMap.TabIndex = 19;
this.groupBoxMap.TabStop = false;
this.groupBoxMap.Text = "Карты";
//
// buttonDeleteMap
//
this.buttonDeleteMap.Location = new System.Drawing.Point(5, 330);
this.buttonDeleteMap.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.buttonDeleteMap.Name = "buttonDeleteMap";
this.buttonDeleteMap.Size = new System.Drawing.Size(250, 58);
this.buttonDeleteMap.TabIndex = 6;
this.buttonDeleteMap.Text = "Удалить карту";
this.buttonDeleteMap.UseVisualStyleBackColor = true;
this.buttonDeleteMap.Click += new System.EventHandler(this.ButtonDeleteMap_Click);
//
// listBoxMaps
//
this.listBoxMaps.FormattingEnabled = true;
this.listBoxMaps.ItemHeight = 25;
this.listBoxMaps.Location = new System.Drawing.Point(5, 189);
this.listBoxMaps.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.listBoxMaps.Name = "listBoxMaps";
this.listBoxMaps.Size = new System.Drawing.Size(248, 129);
this.listBoxMaps.TabIndex = 5;
this.listBoxMaps.SelectedIndexChanged += new System.EventHandler(this.ListBoxMaps_SelectedIndexChanged);
//
// buttonAddMap
//
this.buttonAddMap.Location = new System.Drawing.Point(5, 121);
this.buttonAddMap.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.buttonAddMap.Name = "buttonAddMap";
this.buttonAddMap.Size = new System.Drawing.Size(250, 58);
this.buttonAddMap.TabIndex = 4;
this.buttonAddMap.Text = "Добавить карту";
this.buttonAddMap.UseVisualStyleBackColor = true;
this.buttonAddMap.Click += new System.EventHandler(this.ButtonAddMap_Click);
//
// comboBoxSelectorMap
//
this.comboBoxSelectorMap.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxSelectorMap.FormattingEnabled = true;
this.comboBoxSelectorMap.Items.AddRange(new object[] {
"Простая карта"});
this.comboBoxSelectorMap.Location = new System.Drawing.Point(5, 73);
this.comboBoxSelectorMap.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.comboBoxSelectorMap.Name = "comboBoxSelectorMap";
this.comboBoxSelectorMap.Size = new System.Drawing.Size(248, 33);
this.comboBoxSelectorMap.TabIndex = 3;
//
// textBoxNewMapName
//
this.textBoxNewMapName.Location = new System.Drawing.Point(5, 32);
this.textBoxNewMapName.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.textBoxNewMapName.Name = "textBoxNewMapName";
this.textBoxNewMapName.Size = new System.Drawing.Size(248, 31);
this.textBoxNewMapName.TabIndex = 1;
//
// maskedTextBoxPosition
//
this.maskedTextBoxPosition.Location = new System.Drawing.Point(10, 613);
this.maskedTextBoxPosition.Mask = "00";
this.maskedTextBoxPosition.Name = "maskedTextBoxPosition";
this.maskedTextBoxPosition.Size = new System.Drawing.Size(270, 31);
this.maskedTextBoxPosition.TabIndex = 18;
//
// ButtonDown
//
this.ButtonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.ButtonDown.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("ButtonDown.BackgroundImage")));
this.ButtonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.ButtonDown.Location = new System.Drawing.Point(129, 947);
this.ButtonDown.Name = "ButtonDown";
this.ButtonDown.Size = new System.Drawing.Size(40, 36);
this.ButtonDown.TabIndex = 17;
this.ButtonDown.UseVisualStyleBackColor = true;
this.ButtonDown.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 = ((System.Drawing.Image)(resources.GetObject("ButtonRight.BackgroundImage")));
this.ButtonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.ButtonRight.Location = new System.Drawing.Point(172, 900);
this.ButtonRight.Name = "ButtonRight";
this.ButtonRight.Size = new System.Drawing.Size(40, 36);
this.ButtonRight.TabIndex = 16;
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 = ((System.Drawing.Image)(resources.GetObject("ButtonLeft.BackgroundImage")));
this.ButtonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.ButtonLeft.Location = new System.Drawing.Point(89, 902);
this.ButtonLeft.Name = "ButtonLeft";
this.ButtonLeft.Size = new System.Drawing.Size(40, 36);
this.ButtonLeft.TabIndex = 15;
this.ButtonLeft.UseVisualStyleBackColor = true;
this.ButtonLeft.Click += new System.EventHandler(this.ButtonMove_Click);
//
// ButtonUp
//
this.ButtonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.ButtonUp.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("ButtonUp.BackgroundImage")));
this.ButtonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.ButtonUp.Location = new System.Drawing.Point(129, 852);
this.ButtonUp.Name = "ButtonUp";
this.ButtonUp.Size = new System.Drawing.Size(40, 36);
this.ButtonUp.TabIndex = 14;
this.ButtonUp.UseVisualStyleBackColor = true;
this.ButtonUp.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonMap
//
this.buttonMap.Location = new System.Drawing.Point(18, 787);
this.buttonMap.Name = "buttonMap";
this.buttonMap.Size = new System.Drawing.Size(262, 34);
this.buttonMap.TabIndex = 5;
this.buttonMap.Text = "Посмотреть карту";
this.buttonMap.UseVisualStyleBackColor = true;
this.buttonMap.Click += new System.EventHandler(this.ButtonMap_Click);
//
// buttonStore
//
this.buttonStore.Location = new System.Drawing.Point(16, 721);
this.buttonStore.Name = "buttonStore";
this.buttonStore.Size = new System.Drawing.Size(264, 34);
this.buttonStore.TabIndex = 4;
this.buttonStore.Text = "Посмотреть хранилище";
this.buttonStore.UseVisualStyleBackColor = true;
this.buttonStore.Click += new System.EventHandler(this.ButtonStore_Click);
//
// buttonDelete
//
this.buttonDelete.Location = new System.Drawing.Point(12, 668);
this.buttonDelete.Name = "buttonDelete";
this.buttonDelete.Size = new System.Drawing.Size(268, 34);
this.buttonDelete.TabIndex = 3;
this.buttonDelete.Text = "Удалить машину";
this.buttonDelete.UseVisualStyleBackColor = true;
this.buttonDelete.Click += new System.EventHandler(this.ButtonDelete_Click);
//
// buttonAdd
//
this.buttonAdd.Location = new System.Drawing.Point(5, 551);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(275, 34);
this.buttonAdd.TabIndex = 1;
this.buttonAdd.Text = "Добавить машину";
this.buttonAdd.UseVisualStyleBackColor = true;
this.buttonAdd.Click += new System.EventHandler(this.ButtonAdd_Click);
//
// pictureBoxImage
//
this.pictureBoxImage.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBoxImage.Location = new System.Drawing.Point(0, 33);
this.pictureBoxImage.Name = "pictureBoxImage";
this.pictureBoxImage.Size = new System.Drawing.Size(964, 1003);
this.pictureBoxImage.TabIndex = 1;
this.pictureBoxImage.TabStop = false;
//
// menuStrip
//
this.menuStrip.ImageScalingSize = new System.Drawing.Size(24, 24);
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.файлToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(1264, 33);
this.menuStrip.TabIndex = 2;
this.menuStrip.Text = "menuStrip1";
//
// файл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(69, 29);
this.файлToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(217, 34);
this.SaveToolStripMenuItem.Text = "Сохранение ";
this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// LoadToolStripMenuItem
//
this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(217, 34);
this.LoadToolStripMenuItem.Text = "Загрузка";
this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
// openFileDialog
//
this.openFileDialog.Filter = "text file | *.txt";
//
// saveFileDialog
//
this.saveFileDialog.Filter = "text file | *.txt";
//
// SortBuTypeButton
//
this.SortBuTypeButton.Location = new System.Drawing.Point(20, 454);
this.SortBuTypeButton.Name = "SortBuTypeButton";
this.SortBuTypeButton.Size = new System.Drawing.Size(246, 34);
this.SortBuTypeButton.TabIndex = 20;
this.SortBuTypeButton.Text = "Сортировать по типу";
this.SortBuTypeButton.UseVisualStyleBackColor = true;
this.SortBuTypeButton.Click += new System.EventHandler(this.SortBuTypeButton_Click);
//
// SortByColorButton
//
this.SortByColorButton.Location = new System.Drawing.Point(25, 503);
this.SortByColorButton.Name = "SortByColorButton";
this.SortByColorButton.Size = new System.Drawing.Size(243, 34);
this.SortByColorButton.TabIndex = 21;
this.SortByColorButton.Text = "Сортировать по цвету";
this.SortByColorButton.UseVisualStyleBackColor = true;
this.SortByColorButton.Click += new System.EventHandler(this.SortByColorButton_Click);
//
// FormMapWithSetMachine
//
this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1264, 1036);
this.Controls.Add(this.pictureBoxImage);
this.Controls.Add(this.groupBoxInstruments);
this.Controls.Add(this.menuStrip);
this.MainMenuStrip = this.menuStrip;
this.Name = "FormMapWithSetMachine";
this.Text = "Карта с набором объектов";
this.groupBoxInstruments.ResumeLayout(false);
this.groupBoxInstruments.PerformLayout();
this.groupBoxMap.ResumeLayout(false);
this.groupBoxMap.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxImage)).EndInit();
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private GroupBox groupBoxInstruments;
private Button buttonMap;
private Button buttonStore;
private Button buttonDelete;
private Button buttonAdd;
private PictureBox pictureBoxImage;
private MaskedTextBox maskedTextBoxPosition;
private Button ButtonDown;
private Button ButtonRight;
private Button ButtonLeft;
private Button ButtonUp;
private GroupBox groupBoxMap;
private Button buttonDeleteMap;
private ListBox listBoxMaps;
private Button buttonAddMap;
private ComboBox comboBoxSelectorMap;
private TextBox textBoxNewMapName;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Button SortByColorButton;
private Button SortBuTypeButton;
}
}

View File

@ -0,0 +1,349 @@
using Microsoft.Extensions.Logging;
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 ArmoredVehicle
{
public partial class FormMapWithSetMachine : Form
{
/// <summary>
/// Словарь для выпадающего списка
/// </summary>
private readonly Dictionary<string, AbstractMap> _mapsDict = new()
{
{ "Простая карта", new SimpleMap() },
{ "Вертикальная карта", new VerticalMap() },
{ "Горизонтальная карта", new HorizontalMap() }
};
/// <summary>
/// Объект от коллекции карт
/// </summary>
private readonly MapsCollection _mapsCollection;
/// <summary>
/// Логгер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormMapWithSetMachine(ILogger<FormMapWithSetMachine> logger)
{
InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBoxImage.Width, pictureBoxImage.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.LogInformation("При добавлении карты {0}", comboBoxSelectorMap.SelectedIndex == -1 ? "Не была выбрана карта" : "Не была названа карта");
return;
}
if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text))
{
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogInformation($"Попытка добавить несуществующую карту: {textBoxNewMapName.Text}");
return;
}
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps();
_logger.LogInformation($"Добавлена карта: {textBoxNewMapName.Text}");
}
/// <summary>
/// Выбор карты
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBoxImage.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation("Переход на карту: {0}", 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)
{
_logger.LogInformation($"Попытка удалить несуществующую карту: {textBoxNewMapName.Text}");
return;
}
if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps();
_logger.LogInformation($"Удалена карта: {listBoxMaps.SelectedItem?.ToString()}");
}
}
/// <summary>
/// Добавление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAdd_Click(object sender, EventArgs e)
{
FormMachineConfig formMachine = new();
formMachine.AddEvent(new(AddMachine));
formMachine.Show();
}
/// <summary>
/// Добавление объекта
/// </summary>
/// <param name="machine"></param>
private void AddMachine(DrawingArmoredVehicle machine)
{
try
{
if (listBoxMaps.SelectedIndex == -1)
{
_logger.LogInformation($"Попытка добавления объекта на невыбранную карту");
return;
}
if (machine == null)
{
MessageBox.Show("Необходимо выбрать объект перед добавлением!");
_logger.LogInformation($"Не выбран объект для добавления на карту ");
return;
}
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObject(machine) != -1)
{
pictureBoxImage.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Добавлен объект {machine} на карту ");
}
else
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogInformation($"Не удалось добавить объект {machine} на карту ");
}
}
catch (StorageOverflowException ex)
{
_logger.LogWarning("Ошибка переполнения хранилища: {0}", ex.Message);
MessageBox.Show($"Ошибка переполнения хранилища: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
///<summary>
/// Удаление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonDelete_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text))
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
try
{
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
{
MessageBox.Show("Объект удален");
pictureBoxImage.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation("С карты удален объект {0}", pos);
}
else
{
_logger.LogInformation("Не удалось добавить объект по позиции {0} равен null", pos);
MessageBox.Show("Не удалось удалить объект");
}
}
catch (MachineNotFoundException ex)
{
_logger.LogWarning("Ошибка удаления: {0}", ex.Message);
MessageBox.Show($"Ошибка удаления: {ex.Message}");
}
catch (Exception ex)
{
_logger.LogWarning("Произошла неизвестная ошибка: {0}", ex.Message);
MessageBox.Show($"Неизестная ошибка: {ex.Message}");
}
}
/// <summary>
/// Вывод набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonStore_Click(object sender, EventArgs e)
{
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] == null)
{
return;
}
pictureBoxImage.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
/// <summary>
/// Вывод карты
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonMap_Click(object sender, EventArgs e)
{
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] == null)
{
return;
}
pictureBoxImage.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowOnMap();
}
/// <summary>
/// Перемещение
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] == null)
{
return;
}
//получаем имя кнопки
string name = ((Button)sender)?.Name ?? string.Empty;
Direction dir = Direction.None;
switch (name)
{
case "ButtonUp":
dir = Direction.Up;
break;
case "ButtonDown":
dir = Direction.Down;
break;
case "ButtonLeft":
dir = Direction.Left;
break;
case "ButtonRight":
dir = Direction.Right;
break;
}
pictureBoxImage.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.LogWarning("Успешное сохранение карты в файл: {0}", saveFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Ошибка сохранения карты в файл: {0}", saveFileDialog.FileName);
}
}
}
/// <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);
ReloadMaps();
_logger.LogWarning("Успешная загрузка карты из файла: {0}", saveFileDialog.FileName);
}
catch (LoadFileException ex)
{
MessageBox.Show($"Загрузка не удалась {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Ошибка загрузки карты из файла: {0}", saveFileDialog.FileName);
}
}
}
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SortBuTypeButton_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].Sort(new MachineCompareByType());
pictureBoxImage.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
private void SortByColorButton_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].Sort(new MachineCompareByColor());
pictureBoxImage.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,64 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ArmoredVehicle
{
internal class HorizontalMap : AbstractMap
{
/// <summary>
/// Цвет участка закрытого
/// </summary>
private readonly Brush barrierColor = new SolidBrush(Color.BlueViolet);
/// <summary>
/// Цвет участка открытого
/// </summary>
private readonly Brush roadColor = new SolidBrush(Color.White);
protected override void DrawBarrierPart(Graphics g, int i, int j)
{
g.FillRectangle(barrierColor, i * _size_x, j * _size_y, i * (_size_x + 1), j * (_size_y + 1));
}
protected override void DrawRoadPart(Graphics g, int i, int j)
{
g.FillRectangle(roadColor, i * _size_x, j * _size_y, (i + 1) * (_size_x + 1), (j + 1) * (_size_y + 1));
}
protected override void GenerateMap()
{
_map = new int[50, 50];
_size_x = (float)_width / _map.GetLength(0);
_size_y = (float)_height / _map.GetLength(1);
int counter = 0;
for (int i = 0; i < _map.GetLength(0); ++i)
{
for (int j = 0; j < _map.GetLength(1); ++j)
{
_map[i, j] = _freeRoad;
}
}
while (counter < 5)
{
int x1 = _random.Next(0, 12);
int x2 = _random.Next(12, _map.GetLength(0));
int y1 = _random.Next(0, _map.GetLength(1));
for(int i = x1; i<x2; i++)
{
if (_map[i, y1] == _freeRoad)
{
_map[i, y1] = _barrier;
}
}
counter++;
}
}
}
}

View File

@ -0,0 +1,43 @@
namespace ArmoredVehicle
{
/// <summary>
/// Интерфейс для работы с объектом, прорисовываемым на форме
/// </summary>
internal interface IDrawningObject : IEquatable<IDrawningObject>
{
/// <summary>
/// Шаг перемещения объекта
/// </summary>
public float Step { get; }
/// <summary>
/// Установка позиции объекта
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
/// <param name="width">Ширина полотна</param>
/// <param name="height">Высота полотна</param>
void SetObject(int x, int y, int width, int height);
/// <summary>
/// Изменение направления пермещения объекта
/// </summary>
/// <param name="direction">Направление</param>
/// <returns></returns>
void MoveObject(Direction direction);
/// <summary>
/// Отрисовка объекта
/// </summary>
/// <param name="g"></param>
void DrawningObject(Graphics g);
/// <summary>
/// Получение текущей позиции объекта
/// </summary>
/// <returns></returns>
(float Left, float Right, float Top, float Bottom) GetCurrentPosition();
/// <summary>
/// Получение информации по объекту
/// </summary>
/// <returns></returns>
string GetInfo();
}
}

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ArmoredVehicle
{
internal class LoadFileException : ApplicationException
{
public LoadFileException() : base() { }
public LoadFileException(string message) : base(message) { }
public LoadFileException(string message, Exception exception) : base(message, exception) { }
protected LoadFileException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -0,0 +1,49 @@
namespace ArmoredVehicle
{
internal class MachineCompareByColor : 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 xCar = x as DrawningObject;
var yCar = y as DrawningObject;
if (xCar == null && yCar == null)
{
return 0;
}
if (xCar == null && yCar != null)
{
return 1;
}
if (xCar != null && yCar == null)
{
return -1;
}
if (xCar.GetMachine.ArmoredVehicle.BodyColor == yCar.GetMachine.ArmoredVehicle.BodyColor)
{
return 0;
}
if (xCar.GetMachine.ArmoredVehicle.BodyColor.R.CompareTo(yCar.GetMachine.ArmoredVehicle.BodyColor.R) == 0)
{
if (xCar.GetMachine.ArmoredVehicle.BodyColor.R.CompareTo(yCar.GetMachine.ArmoredVehicle.BodyColor.R) == 0)
{
return xCar.GetMachine.ArmoredVehicle.BodyColor.B.CompareTo(yCar.GetMachine.ArmoredVehicle.BodyColor.B);
}
else return xCar.GetMachine.ArmoredVehicle.BodyColor.G.CompareTo(yCar.GetMachine.ArmoredVehicle.BodyColor.G);
}
else return xCar.GetMachine.ArmoredVehicle.BodyColor.R.CompareTo(yCar.GetMachine.ArmoredVehicle.BodyColor.R);
}
}
}

View File

@ -0,0 +1,49 @@
namespace ArmoredVehicle
{
internal class MachineCompareByType : 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 xMachine= x as DrawningObject;
var yMachine = y as DrawningObject;
if (xMachine == null && yMachine == null)
{
return 0;
}
if (xMachine == null && yMachine != null)
{
return 1;
}
if (xMachine != null && yMachine == null)
{
return -1;
}
if (xMachine.GetMachine.GetType().Name != yMachine.GetMachine.GetType().Name)
{
if (xMachine.GetMachine.GetType().Name == "DrawingArmoredVehicle")
{
return -1;
}
return 1;
}
var speedCompare = xMachine.GetMachine.ArmoredVehicle.Speed.CompareTo(yMachine.GetMachine.ArmoredVehicle.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return xMachine.GetMachine.ArmoredVehicle.Weight.CompareTo(yMachine.GetMachine.ArmoredVehicle.Weight);
}
}
}

View File

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

View File

@ -39,6 +39,8 @@
this.toolStripStatusLabelWeight = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStripStatusLabelColor = new System.Windows.Forms.ToolStripStatusLabel();
this.statusStrip = new System.Windows.Forms.StatusStrip();
this.TankButton = new System.Windows.Forms.Button();
this.ChooseButton = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.DrawingPictureBox)).BeginInit();
this.statusStrip.SuspendLayout();
this.SuspendLayout();
@ -107,7 +109,7 @@
this.DrawingPictureBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.DrawingPictureBox.Location = new System.Drawing.Point(0, 0);
this.DrawingPictureBox.Name = "DrawingPictureBox";
this.DrawingPictureBox.Size = new System.Drawing.Size(800, 418);
this.DrawingPictureBox.Size = new System.Drawing.Size(800, 450);
this.DrawingPictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.DrawingPictureBox.TabIndex = 7;
this.DrawingPictureBox.TabStop = false;
@ -144,18 +146,40 @@
this.statusStrip.TabIndex = 8;
this.statusStrip.Text = "statusStrip1";
//
// TankButton
//
this.TankButton.Location = new System.Drawing.Point(139, 365);
this.TankButton.Name = "TankButton";
this.TankButton.Size = new System.Drawing.Size(143, 34);
this.TankButton.TabIndex = 14;
this.TankButton.Text = "Модификация";
this.TankButton.UseVisualStyleBackColor = true;
this.TankButton.Click += new System.EventHandler(this.TankButton_Click);
//
// ChooseButton
//
this.ChooseButton.Location = new System.Drawing.Point(484, 362);
this.ChooseButton.Name = "ChooseButton";
this.ChooseButton.Size = new System.Drawing.Size(143, 34);
this.ChooseButton.TabIndex = 15;
this.ChooseButton.Text = "Выбрать";
this.ChooseButton.UseVisualStyleBackColor = true;
this.ChooseButton.Click += new System.EventHandler(this.ChooseButton_Click);
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.ChooseButton);
this.Controls.Add(this.TankButton);
this.Controls.Add(this.ButtonDown);
this.Controls.Add(this.ButtonRight);
this.Controls.Add(this.ButtonLeft);
this.Controls.Add(this.ButtonUp);
this.Controls.Add(this.CreateButton);
this.Controls.Add(this.DrawingPictureBox);
this.Controls.Add(this.statusStrip);
this.Controls.Add(this.DrawingPictureBox);
this.MinimumSize = new System.Drawing.Size(210, 50);
this.Name = "MainForm";
this.Text = "Военная машина";
@ -179,5 +203,7 @@
private ToolStripStatusLabel toolStripStatusLabelWeight;
private ToolStripStatusLabel toolStripStatusLabelColor;
private StatusStrip statusStrip;
private Button TankButton;
private Button ChooseButton;
}
}

View File

@ -6,8 +6,9 @@ namespace ArmoredVehicle
public MainForm()
{
InitializeComponent();
//this.MinimumSize = new System.Drawing.Size(300, 250);
}
public DrawingArmoredVehicle SelectedMachine { get; private set; }
/// <summary>
/// Ìåòîä ïðîðèñîâêè ìàøèíû
/// </summary>
@ -34,13 +35,26 @@ namespace ArmoredVehicle
private void CreateButton_Click(object sender, EventArgs e)
{
Random rnd = new();
_ArmoredVehicle = new DrawingArmoredVehicle();
_ArmoredVehicle.Init(rnd.Next(100, 300), rnd.Next(1000, 2000), Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256)));
Color color = Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
_ArmoredVehicle = new DrawingArmoredVehicle(rnd.Next(100, 300), rnd.Next(1000, 2000),
color);
SetData();
Draw();
}
private void SetData()
{
Random rnd = new();
_ArmoredVehicle.SetPosition(/*rnd.Next(0, 100)*/ -10, rnd.Next(0, 100), DrawingPictureBox.Width, DrawingPictureBox.Height);
toolStripStatusLabelSpeed.Text = $"Ñêîðîñòü: {_ArmoredVehicle.ArmoredVehicle.Speed}";
toolStripStatusLabelWeight.Text = $"Âåñ: {_ArmoredVehicle.ArmoredVehicle.Weight}";
toolStripStatusLabelColor.Text = $"Öâåò: {_ArmoredVehicle.ArmoredVehicle.BodyColor.Name}";
Draw();
}
/// <summary>
/// Èçìåíåíèå ðàçìåðîâ ôîðìû
@ -79,5 +93,41 @@ namespace ArmoredVehicle
_ArmoredVehicle?.ChangeBorders(DrawingPictureBox.Width, DrawingPictureBox.Height);
Draw();
}
private void TankButton_Click(object sender, EventArgs e)
{
Random rnd = new();
Color color = Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
Color dopColor = Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256));
ColorDialog dialogDop = new();
if (dialogDop.ShowDialog() == DialogResult.OK)
{
dopColor = dialogDop.Color;
}
_ArmoredVehicle = new DrawingTank(rnd.Next(100, 300),
rnd.Next(1000, 2000),
color,
dopColor,
Convert.ToBoolean(rnd.Next(0, 2)),
Convert.ToBoolean(rnd.Next(0, 2)));
SetData();
Draw();
}
/// <summary>
/// Îáđŕáîňęŕ íŕćŕňč˙ ęíîďęč "Âűáđŕňü"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ChooseButton_Click(object sender, EventArgs e)
{
SelectedMachine = _ArmoredVehicle;
DialogResult = DialogResult.OK;
}
}
}

View File

@ -61,7 +61,7 @@
<data name="ButtonDown.BackgroundImage" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
iVBORw0KGgoAAAANSUhEUgAABkAAAAZACAIAAACubhnwAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAO
vwAADr8BOAVTJAAAy5RJREFUeF7s/emTZGd54O/3L9eqbkkI1GKxkUHsCA8gsXhACBNsxoBsY2BYhIkY
vAAADrwBlbxySQAAy5RJREFUeF7s/emTZGd54O/3L9eqbkkI1GKxkUHsCA8gsXhACBNsxoBsY2BYhIkY
ApgAIeMxYRADg74QNjJbBMYwrIPD0oBZBHjAbGYkbGMW4wn+GI/VXZVL+XdX3tmHstDSLVU/dVfmdb04
8WTptfq583Oec/LIvwFAbV/+8pf/fwDU0+v1cnHkyJG4vu1tb1v+ww0A+03AAqA6AQugJgELgGYELACq
E7AAahKwAGhGwAKgOgELoCYBC4BmBCwAqhOwAGoSsABoRsACoDoBC6AmAQuAZgQsAKoTsABqErAAaEbA
@ -936,7 +936,7 @@
<data name="ButtonRight.BackgroundImage" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
iVBORw0KGgoAAAANSUhEUgAABkAAAAZACAIAAACubhnwAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAO
vwAADr8BOAVTJAAAtnhJREFUeF7s3fmbZXdVL/7NHs6p6m4ydRIvQwgJiQgSCJDwRUaVYICAPqjhEmVw
vAAADrwBlbxySQAAtnhJREFUeF7s3fmbZXdVL/7NHs6p6m4ydRIvQwgJiQgSCJDwRUaVYICAPqjhEmVw
iAo3xAjKKBBl8MEQUO5FgSBwITIJ6FUMgyZBCSjivX9O0nXG+q7aq2p7aELS6VTX2afq9frh86z92QdI
uqvO4367PmsXmwAAAADQYwIsAAAAAHpNgAUAAABArwmwAAAAAOg1ARYAAAAAvSbAAgAAAKDXBFgAAAAA
9JoACwAAAIBeE2ABAAAA0GsCLAAAAAB6TYAFAAAAQK8JsAAAAADoNQEWAAAAAL0mwAIAAACg1wRYAAAA
@ -1721,7 +1721,7 @@
<data name="ButtonLeft.BackgroundImage" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
iVBORw0KGgoAAAANSUhEUgAABkAAAAZACAIAAACubhnwAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAO
vwAADr8BOAVTJAAAt0tJREFUeF7s3fmXbHdZL/7qGvucEwicDBgkEIYwKCEB4mJIIiKwkEEGXQHBCA5c
vAAADrwBlbxySQAAt0tJREFUeF7s3fmXbHdZL/7qGvucEwicDBgkEIYwKCEB4mJIIiKwkEEGXQHBCA5c
hst0EQ34lcGrQBACsq5BJhUvYYoQVCZRQlBALsa77h9z17rprtq7Nt+n9lO9LUJCzsnp7r2r6/X64bOe
/al2mdNdVWvtN8/n2b0fAgAAAECHCbAAAAAA6DQBFgAAAACdJsACAAAAoNMEWAAAAAB0mgALAAAAgE4T
YAEAAADQaQIsAAAAADpNgAUAAABApwmwAAAAAOg0ARYAAAAAnSbAAgAAAKDTBFgAAAAAdJoACwAAAIBO
@ -2509,7 +2509,7 @@
<data name="ButtonUp.BackgroundImage" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
iVBORw0KGgoAAAANSUhEUgAABkAAAAZACAIAAACubhnwAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAO
vwAADr8BOAVTJAAAy01JREFUeF7s3fm/ZFV5L/7TVbWr6nTTjM0QBUQhikMEgsQBiYYEoqJGo8YxJlGD
vAAADrwBlbxySQAAy01JREFUeF7s3fm/ZFV5L/7TVbWr6nTTjM0QBUQhikMEgsQBiYYEoqJGo8YxJlGD
XxViNIng1WBiDEQxwRgvDhiNosYB472KQyBgohLuNa/c1/1fbuxTs9/n7Kd6WSLQ0+lzani/f1ivtTcK
3edU7f2sz15r7bUfAwAAAMAcE2ABAAAAMNcEWAAAAADMNQEWAAAAAHNNgAUAAADAXBNgAQAAADDXBFgA
AAAAzDUBFgAAAABzTYAFAAAAwFwTYAEAAAAw1wRYAAAAAMw1ARYAAAAAc02ABQAAAMBcE2ABAAAAMNcE

View File

@ -0,0 +1,225 @@
namespace ArmoredVehicle
{
/// <summary>
/// Карта с набром объектов под нее
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
internal class MapWithSetMachineGeneric<T, U>
where T : class, IDrawningObject, IEquatable<T>
where U : AbstractMap
{
/// <summary>
/// Ширина окна отрисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна отрисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Размер занимаемого объектом места (ширина)
/// </summary>
private readonly int _placeSizeWidth = 210;
/// <summary>
/// Размер занимаемого объектом места (высота)
/// </summary>
private readonly int _placeSizeHeight = 90;
/// <summary>
/// Набор объектов
/// </summary>
private readonly SetMachineGeneric<T> _setMachines;
/// <summary>
/// Карта
/// </summary>
private readonly U _map;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
/// <param name="map"></param>
public MapWithSetMachineGeneric(int picWidth, int picHeight, U map)
{
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_setMachines = new SetMachineGeneric<T>(width * height);
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_map = map;
}
/// <summary>
/// Перегрузка оператора сложения
/// </summary>
/// <param name="map"></param>
/// <param name="machine"></param>
/// <returns></returns>
public static int operator +(MapWithSetMachineGeneric<T, U> map, T machine)
{
return map._setMachines.Insert(machine);
}
/// <summary>
/// Перегрузка оператора вычитания
/// </summary>
/// <param name="map"></param>
/// <param name="position"></param>
/// <returns></returns>
public static T operator -(MapWithSetMachineGeneric<T, U> map, int position)
{
return map._setMachines.Remove(position);
}
/// <summary>
/// Вывод всего набора объектов
/// </summary>
/// <returns></returns>
public Bitmap ShowSet()
{
Bitmap bmp = new(_pictureWidth, _pictureHeight);
Graphics gr = Graphics.FromImage(bmp);
DrawBackground(gr);
DrawMachine(gr);
return bmp;
}
/// <summary>
/// Просмотр объекта на карте
/// </summary>
/// <returns></returns>
public Bitmap ShowOnMap()
{
Shaking();
foreach (var machine in _setMachines.GetMachine())
{
return _map.CreateMap(_pictureWidth, _pictureHeight, machine);
}
return new(_pictureWidth, _pictureHeight);
}
/// <summary>
/// Перемещение объекта по крате
/// </summary>
/// <param name="direction"></param>
/// <returns></returns>
public Bitmap MoveObject(Direction direction)
{
if (_map != null)
{
return _map.MoveObject(direction);
}
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 machine in _setMachines.GetMachine())
{
data += $"{machine.GetInfo()}{separatorData}";
}
return data;
}
/// <summary>
/// Загрузка списка из массива строк
/// </summary>
/// <param name="records"></param>
public void LoadData(string[] records)
{
foreach (var rec in records)
{
_setMachines.Insert(DrawningObject.Create(rec) as T);
}
}
public void Sort(IComparer<T> comparer)
{
_setMachines.SortSet(comparer);
}
/// <summary>
/// "Взбалтываем" набор, чтобы все элементы оказались в начале
/// </summary>
private void Shaking()
{
int j = _setMachines.Count - 1;
for (int i = 0; i < _setMachines.Count; i++)
{
if (_setMachines[i] == null)
{
for (; j > i; j--)
{
var car = _setMachines[j];
if (car != null)
{
_setMachines.Insert(car, i);
_setMachines.Remove(j);
break;
}
}
if (j <= i)
{
return;
}
}
}
}
/// <summary>
/// Метод отрисовки фона
/// </summary>
/// <param name="g"></param>
private void DrawBackground(Graphics g)
{
Pen pen = new(Color.LawnGreen, 5);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j)
{//линия рамзетки места
int dop = 0;
if(i>0 && j>0)
{
dop = 30;
}
g.DrawRectangle(pen, new Rectangle(i * _placeSizeWidth + dop, j * _placeSizeHeight + dop, i * _placeSizeWidth + _placeSizeWidth, j * _placeSizeHeight + _placeSizeHeight));
}
}
}
/// <summary>
/// Метод прорисовки объектов
/// </summary>
/// <param name="g"></param>
private void DrawMachine(Graphics g)
{
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
int currentWidth = 0;
int currentHeight = 0;
foreach (var machine in _setMachines.GetMachine())
{
int dop = 0;
if (currentWidth > 0 && currentHeight > 0)
{
dop = 30;
}
machine.SetObject(currentWidth * _placeSizeWidth + dop,
currentHeight * _placeSizeHeight + dop,
_pictureWidth, _pictureHeight);
machine?.DrawningObject(g);
if (currentWidth < width - 1)
{
currentWidth++;
}
else
{
currentWidth = 0;
currentHeight++;
}
if (currentHeight > height) return;
}
}
}
}

View File

@ -0,0 +1,170 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ArmoredVehicle
{
/// <summary>
/// Класс для хранения коллекции карт
/// </summary>
internal class MapsCollection
{
/// <summary>
/// Словарь (хранилище) с картами
/// </summary>
readonly Dictionary<string, MapWithSetMachineGeneric<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,
MapWithSetMachineGeneric<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))
{
MessageBox.Show("Такая карта уже есть");
return;
}
else
{
var NewElem = new MapWithSetMachineGeneric<IDrawningObject, AbstractMap>(
_pictureWidth, _pictureHeight, map);
_mapStorages.Add(name, NewElem);
}
}
/// <summary>
/// Удаление карты
/// </summary>
/// <param name="name">Название карты</param>
public void DelMap(string name)
{
if (Keys.Contains(name))
{
_mapStorages.Remove(name);
}
else
{
MessageBox.Show("Такой карты нет");
return;
}
}
/// <summary>
/// Доступ к парковке
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public MapWithSetMachineGeneric<IDrawningObject, AbstractMap> this[string ind]
{
get
{
if(Keys.Contains(ind))
{
return _mapStorages[ind];
}
MessageBox.Show("Такой карты нет");
return null;
}
}
/// <summary>
/// Сохранение информации по машинам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns></returns>
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter fs = new(filename))
{
fs.Write($"MapsCollection{Environment.NewLine}");
foreach (var storage in _mapStorages)
{
fs.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 LoadFileException($"Файл {filename} не найден");
}
string bufferTextFromFile = "";
using (StreamReader sr = new(filename))
{
string checkMap = sr.ReadLine();
if (!checkMap.Contains("MapsCollection"))
{
throw new LoadFileException($"Неверный формат данных в файле {filename}");
}
bufferTextFromFile = sr.ReadLine();
_mapStorages.Clear();
while (bufferTextFromFile != null)
{
var strs = bufferTextFromFile.Split(separatorDict);
AbstractMap map = null;
switch (strs[1])
{
case "SimpleMap":
map = new SimpleMap();
break;
case "VertivalMap":
map = new VerticalMap();
break;
case "HorizontalMap":
map = new HorizontalMap();
break;
}
_mapStorages.Add(strs[0], new MapWithSetMachineGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[strs[0]].LoadData(strs[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
bufferTextFromFile = sr.ReadLine();
}
}
}
}
}

View File

@ -1,3 +1,9 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace ArmoredVehicle
{
internal static class Program
@ -8,10 +14,31 @@ namespace ArmoredVehicle
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new MainForm());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormMapWithSetMachine>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormMapWithSetMachine>()
.AddLogging(option =>
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: "appsettings.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

View File

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

View File

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

View File

@ -0,0 +1,133 @@
namespace ArmoredVehicle
{
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T"></typeparam>
internal class SetMachineGeneric<T>
where T : class, IEquatable<T>
{
/// <summary>
/// Список объектов, которые храним
/// </summary>
private readonly List<T> _places;
private readonly int _maxCount;
/// <summary>
/// Количество объектов в списке
/// </summary>
public int Count => _places.Count;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetMachineGeneric(int count)
{
_maxCount = count;
_places = new List<T>();
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="machine">Добавляемая машина</param>
/// <returns></returns>
public int Insert(T machine)
{
if (Count + 1 <= _maxCount) return Insert(machine, 0);
else throw new StorageOverflowException(_maxCount);
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="machine">Добавляемая машина</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public int Insert(T machine, int position)
{
if(_places.All(p => p.Equals(machine) == false))
{
if (position >= _maxCount) throw new StorageOverflowException(_maxCount);
_places.Insert(position, machine);
return position;
}
return -1;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T Remove(int position)
{
if (position < _maxCount && position >= 0)
{
if (_places.ElementAt(position) != null)
{
T result = _places.ElementAt(position);
_places.RemoveAt(position);
return result;
}
else throw new MachineNotFoundException(position);
}
else throw new MachineNotFoundException(position);
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T this[int position]
{
get
{
if (position < _maxCount && position >= 0)
{
return _places.ElementAt(position);
}
return null;
}
set
{
if (position < _maxCount && position >= 0)
{
Insert(this[position], position);
}
}
}
/// <summary>
/// Проход по набору до первого пустого
/// </summary>
/// <returns></returns>
public IEnumerable<T> GetMachine()
{
foreach (var machine in _places)
{
if (machine != null)
{
yield return machine;
}
else
{
yield break;
}
}
}
/// <summary>
/// Сортировка набора объектов
/// </summary>
/// <param name="comparer"></param>
public void SortSet(IComparer<T> comparer)
{
if (comparer == null)
{
return;
}
_places.Sort(comparer);
}
}
}

View File

@ -0,0 +1,52 @@
namespace ArmoredVehicle
{
/// <summary>
/// Простая реализация абсрактного класса AbstractMap
/// </summary>
internal class SimpleMap : AbstractMap
{
/// <summary>
/// Цвет участка закрытого
/// </summary>
private readonly Brush barrierColor = new SolidBrush(Color.Black);
/// <summary>
/// Цвет участка открытого
/// </summary>
private readonly Brush roadColor = new SolidBrush(Color.Gray);
protected override void DrawBarrierPart(Graphics g, int i, int j)
{
g.FillRectangle(barrierColor, i * _size_x, j * _size_y, i * (_size_x + 1), j * (_size_y + 1));
}
protected override void DrawRoadPart(Graphics g, int i, int j)
{
g.FillRectangle(roadColor, i * _size_x, j * _size_y, (i+1) * (_size_x + 1), (j+1) * (_size_y + 1));
}
protected override void GenerateMap()
{
_map = new int[50, 50];
_size_x = (float)_width / _map.GetLength(0);
_size_y = (float)_height / _map.GetLength(1);
int counter = 0;
for (int i = 0; i < _map.GetLength(0); ++i)
{
for (int j = 0; j < _map.GetLength(1); ++j)
{
_map[i, j] = _freeRoad;
}
}
while (counter < 50)
{
int x = _random.Next(0, 50);
int y = _random.Next(0, 50);
if (_map[x, y] == _freeRoad)
{
_map[x, y] = _barrier;
counter++;
}
}
}
}
}

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

@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ArmoredVehicle
{
internal class TankEnity : ArmoredVehicleEntity
{
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес танка</param>
/// <param name="bodyColor">Цвет башни</param>
/// <param name="dopColor">Дополнительный цвет</param>
/// <param name="MachineGun">Признак наличия пулемета</param>
/// <param name="Tower">Признак наличия башни</param>
public TankEnity(int speed, float weight, Color bodyColor, Color dopColor, bool machineGun, bool tower) : base(speed, weight, bodyColor)
{
DopColor = dopColor;
MachineGun = machineGun;
Tower = tower;
}
/// <summary>
/// Дополнительный цвет
/// </summary>
public Color DopColor { get; private set; }
/// <summary>
/// Признак наличия пулемета
/// </summary>
public bool MachineGun { get; private set; }
/// <summary>
/// Признак наличия башни
/// </summary>
public bool Tower { get; private set; }
}
}

View File

@ -0,0 +1,62 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ArmoredVehicle
{
internal class VerticalMap : AbstractMap
{ /// <summary>
/// Цвет участка закрытого
/// </summary>
private readonly Brush barrierColor = new SolidBrush(Color.Brown);
/// <summary>
/// Цвет участка открытого
/// </summary>
private readonly Brush roadColor = new SolidBrush(Color.LightGray);
protected override void DrawBarrierPart(Graphics g, int i, int j)
{
g.FillRectangle(barrierColor, i * _size_x, j * _size_y, i * (_size_x + 1), j * (_size_y + 1));
}
protected override void DrawRoadPart(Graphics g, int i, int j)
{
g.FillRectangle(roadColor, i * _size_x, j * _size_y, (i + 1) * (_size_x + 1), (j + 1) * (_size_y + 1));
}
protected override void GenerateMap()
{
_map = new int[50, 50];
_size_x = (float)_width / _map.GetLength(0);
_size_y = (float)_height / _map.GetLength(1);
int counter = 0;
for (int i = 0; i < _map.GetLength(0); ++i)
{
for (int j = 0; j < _map.GetLength(1); ++j)
{
_map[i, j] = _freeRoad;
}
}
while (counter < 7)
{
int x1 = _random.Next(0, 12);
int x2 = _random.Next(12, _map.GetLength(0));
int y1 = _random.Next(0, _map.GetLength(1));
for (int i = x1; i < x2; i++)
{
if (_map[y1, i] == _freeRoad)
{
_map[y1, i] = _barrier;
}
}
counter++;
}
}
}
}

View File

@ -0,0 +1,36 @@
namespace ArmoredVehicle
{
partial class appsettings
{
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Код, автоматически созданный конструктором компонентов
/// <summary>
/// Требуемый метод для поддержки конструктора не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
}
}

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>