Compare commits

..

1 Commits

29 changed files with 18 additions and 2969 deletions

View File

@ -1,177 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirFighter
{
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)
{
// Проверка коллизии
(float Left, float Right, float Top, float Bottom) = _drawningObject.GetCurrentPosition();
switch (direction)
{
case Direction.Right:
if (Right + _drawningObject.Step < _width)
{
Left += _drawningObject.Step;
Right += _drawningObject.Step;
}
break;
case Direction.Left:
if (Left - _drawningObject.Step >= 0)
{
Left -= _drawningObject.Step;
Right -= _drawningObject.Step;
}
break;
case Direction.Up:
if (Top - _drawningObject.Step >= 0)
{
Top -= _drawningObject.Step;
Bottom -= _drawningObject.Step;
}
break;
case Direction.Down:
if (Bottom + _drawningObject.Step < _height)
{
Top += _drawningObject.Step;
Bottom += _drawningObject.Step;
}
break;
}
if (CheckBarrier((int)Right, (int)Left, (int)Top, (int)Bottom) == 1)
{
_drawningObject.MoveObject(direction);
}
return DrawMapWithObject();
}
private int CheckBarrier(int Right, int Left, int Top, int Bottom)
{
if(Left < 0 || Top < 0 || Right > _width || Bottom > _height)
{
return 2;
}
for (int i = (int)(Top / _size_y); i <= (int)(Bottom / _size_y); i++)
{
for (int j = (int)(Left / _size_x); j <= (int)(Right / _size_x); j++)
{
if (_map[i, j] == _barrier)
return 0;
}
}
return 1;
}
private bool SetObjectOnMap()
{
if (_drawningObject == null || _map == null)
{
return false;
}
int x = _random.Next(0, 10);
int y = _random.Next(0, 10);
_drawningObject.SetObject(x, y, _width, _height);
// Првоерка, что объект не "накладывается" на закрытые участки
(float Left, float Right, float Top, float Bottom) = _drawningObject.GetCurrentPosition();
float tempBottom = Bottom;
float tempTop = Top;
while (CheckBarrier((int)Right, (int)Left, (int)Top, (int)Bottom) == 0)
{
int flag = 0;
while (flag == 0)
{
y += (int)_size_y;
Top += (int)_size_y;
Bottom += (int)_size_y;
_drawningObject.SetObject(x, y, _width, _height);
flag = CheckBarrier((int)Right, (int)Left, (int)Top, (int)Bottom);
}
if (flag == 1)
{
return true;
}
x += (int)_size_x;
Left += (int)_size_x;
Right += (int)_size_x;
y = (int)tempTop;
Top = (int)tempTop;
Bottom = (int)tempBottom;
}
return false;
}
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, j, i);
}
else if (_map[i, j] == _barrier)
{
DrawBarrierPart(gr, j, i);
}
}
}
_drawningObject.DrawningObject(gr);
return bmp;
}
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)
{
if (other == null || _height != other._height || _width != other._width || _size_x != other._size_x || _size_y != other._size_y)
{
return false;
}
for(int i = 0; i < _map.GetLength(0); i++)
{
for(int j = 0; j < _map.GetLength(1); j++)
{
if(_map[i, j] != other._map[i, j])
{
return false;
}
}
}
return true;
}
}
}

View File

@ -8,27 +8,6 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<None Remove="serilogConfig.json" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="serilogConfig.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" 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>

View File

@ -1,65 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirFighter
{
internal class AirFighterCompareByColor : 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 xAirFighter = x as DrawningObjectAirFighter;
var yAirFighter = y as DrawningObjectAirFighter;
if (xAirFighter == null && yAirFighter == null)
{
return 0;
}
if (xAirFighter == null && yAirFighter != null)
{
return 1;
}
if (xAirFighter != null && yAirFighter == null)
{
return -1;
}
var xEntityAirFighter = xAirFighter.GetAirFighter.AirFighter;
var yEntityAirFighter = yAirFighter.GetAirFighter.AirFighter;
var colorCompare = xEntityAirFighter.BodyColor.ToArgb().CompareTo(yEntityAirFighter.BodyColor.ToArgb());
if (colorCompare != 0)
{
return colorCompare;
}
if(xEntityAirFighter is EntityUpgradeAirFighter xUpgradeAirFighter && yEntityAirFighter is EntityUpgradeAirFighter yUpgradeAirFighter)
{
var dopColorCompare = xUpgradeAirFighter.DopColor.ToArgb().CompareTo(yUpgradeAirFighter.DopColor.ToArgb());
if (dopColorCompare != 0)
{
return dopColorCompare;
}
}
var speedCompare = xAirFighter.GetAirFighter.AirFighter.Speed.CompareTo(yAirFighter.GetAirFighter.AirFighter.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return xAirFighter.GetAirFighter.AirFighter.Weight.CompareTo(yAirFighter.GetAirFighter.AirFighter.Weight);
}
}
}

View File

@ -1,55 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirFighter
{
internal class AirFighterCompareByType : 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 xAirFighter = x as DrawningObjectAirFighter;
var yAirFighter = y as DrawningObjectAirFighter;
if (xAirFighter == null && yAirFighter == null)
{
return 0;
}
if (xAirFighter == null && yAirFighter != null)
{
return 1;
}
if (xAirFighter != null && yAirFighter == null)
{
return -1;
}
if (xAirFighter.GetAirFighter.GetType().Name != yAirFighter.GetAirFighter.GetType().Name)
{
if (xAirFighter.GetAirFighter.GetType().Name == "DrawningAirFighter")
{
return -1;
}
return 1;
}
var speedCompare = xAirFighter.GetAirFighter.AirFighter.Speed.CompareTo(yAirFighter.GetAirFighter.AirFighter.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return xAirFighter.GetAirFighter.AirFighter.Weight.CompareTo(yAirFighter.GetAirFighter.AirFighter.Weight);
}
}
}

View File

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

View File

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

View File

@ -9,20 +9,20 @@ namespace AirFighter
/// <summary>
/// Класс отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningAirFighter
internal class DrawningAirFighter
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityAirFighter AirFighter { protected set; get; }
public EntityAirFighter AirFighter { private set; get; }
/// <summary>
/// Левая координата отрисовки самолета
/// </summary>
protected float _startPosX;
private float _startPosX;
/// <summary>
/// Верхняя кооридната отрисовки самолета
/// </summary>
protected float _startPosY;
private float _startPosY;
/// <summary>
/// Ширина окна отрисовки
/// </summary>
@ -45,15 +45,10 @@ namespace AirFighter
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес самолета</param>
/// <param name="bodyColor">Цвет кузова</param>
public DrawningAirFighter(int speed, float weight, Color bodyColor)
public void Init(int speed, float weight, Color bodyColor)
{
AirFighter = new EntityAirFighter(speed, weight, bodyColor);
}
protected DrawningAirFighter(int speed, float weight, Color bodyColor, int airFighterWight, int airFighterHeight) :
this(speed, weight, bodyColor)
{
_airFighterWidth = airFighterWight;
_airFighterHeight = airFighterHeight;
AirFighter = new EntityAirFighter();
AirFighter.Init(speed, weight, bodyColor);
}
/// <summary>
/// Установка позиции самолета
@ -129,7 +124,7 @@ namespace AirFighter
/// <summary>
/// Отрисовка самолета
/// </summary>
public virtual void DrawAirFighter(Graphics g)
public void DrawAirFighter(Graphics g)
{
if (_startPosX < 0 || _startPosY < 0 || !_pictureHeight.HasValue || !_pictureWidth.HasValue)
{
@ -188,13 +183,5 @@ namespace AirFighter
_startPosY = _pictureHeight.Value - _airFighterHeight;
}
}
/// <summary>
/// Получение текущей позиции объекта
/// </summary>
/// <returns></returns>
public (float Left, float Right, float Top, float Bottom) GetCurrentPosition()
{
return (_startPosX, _startPosX + _airFighterWidth, _startPosY, _startPosY + _airFighterHeight);
}
}
}

View File

@ -1,90 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirFighter
{
internal class DrawningObjectAirFighter : IDrawningObject
{
private DrawningAirFighter _airFighter = null;
public float Step => _airFighter?.AirFighter.Step ?? 0;
public DrawningAirFighter GetAirFighter => _airFighter;
public DrawningObjectAirFighter(DrawningAirFighter airFighter)
{
_airFighter = airFighter;
}
void IDrawningObject.DrawningObject(Graphics g)
{
_airFighter.DrawAirFighter(g);
}
public (float Left, float Right, float Top, float Bottom) GetCurrentPosition()
{
return _airFighter?.GetCurrentPosition() ?? default;
}
public void MoveObject(Direction direction)
{
_airFighter?.MoveTransport(direction);
}
public void SetObject(int x, int y, int width, int height)
{
_airFighter?.SetPosition(x, y, width, height);
}
public string GetInfo() => _airFighter?.GetDataForSave();
public static IDrawningObject Create(string data) => new DrawningObjectAirFighter(data.CreateDrawningCar());
public bool Equals(IDrawningObject? other)
{
if (other == null)
{
return false;
}
var otherAirFighter = other as DrawningObjectAirFighter;
if (otherAirFighter == null)
{
return false;
}
var airFighter = _airFighter.AirFighter;
var otherAirFighterAirFighter = otherAirFighter._airFighter.AirFighter;
if (airFighter.Speed != otherAirFighterAirFighter.Speed)
{
return false;
}
if (airFighter.Weight != otherAirFighterAirFighter.Weight)
{
return false;
}
if (airFighter.BodyColor != otherAirFighterAirFighter.BodyColor)
{
return false;
}
if(airFighter is EntityUpgradeAirFighter upgradeAirFighter && otherAirFighterAirFighter is EntityUpgradeAirFighter upgradeOtherAirFighter)
{
if(upgradeAirFighter.DopWing != upgradeOtherAirFighter.DopWing)
{
return false;
}
if(upgradeAirFighter.Rocket != upgradeAirFighter.Rocket)
{
return false;
}
if(upgradeAirFighter.DopColor != upgradeOtherAirFighter.DopColor)
{
return false;
}
}else if(airFighter is EntityUpgradeAirFighter || otherAirFighterAirFighter is EntityUpgradeAirFighter)
{
return false;
}
return true;
}
}
}

View File

@ -1,99 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirFighter
{
internal class DrawningUpgradeAirFighter : DrawningAirFighter
{
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed"></param>
/// <param name="weight"></param>
/// <param name="bodyColor"></param>
/// <param name="dopColor"></param>
/// <param name="dopWing"></param>
/// <param name="rocket"></param>
public DrawningUpgradeAirFighter(int speed, float weight, Color bodyColor, Color dopColor, bool dopWing, bool rocket) :
base(speed, weight, bodyColor, 85, 80)
{
AirFighter = new EntityUpgradeAirFighter(speed, weight, bodyColor, dopColor, dopWing, rocket);
}
public override void DrawAirFighter(Graphics g)
{
if(AirFighter is not EntityUpgradeAirFighter upgradeAirFighter)
{
return;
}
Pen pen = new(Color.Black);
Brush dopBrush = new SolidBrush(upgradeAirFighter.DopColor);
_startPosX += 5;
_startPosY += 5;
base.DrawAirFighter(g);
_startPosX -= 5;
_startPosY -= 5;
if (upgradeAirFighter.DopWing)
{
PointF[] _pointBackWing =
{
new PointF(_startPosX, _startPosY + 35),
new PointF(_startPosX, _startPosY + 45),
new PointF(_startPosX + 10, _startPosY + 40)
};
PointF[] _pointLeftWing =
{
new PointF(_startPosX + 50, _startPosY + 35),
new PointF(_startPosX + 55, _startPosY + 30),
new PointF(_startPosX + 65, _startPosY + 35)
};
PointF[] _pointRightWing =
{
new PointF(_startPosX + 50, _startPosY + 45),
new PointF(_startPosX + 55, _startPosY + 50),
new PointF(_startPosX + 65, _startPosY + 45)
};
g.FillPolygon(dopBrush, _pointBackWing);
g.FillPolygon(dopBrush, _pointLeftWing);
g.FillPolygon(dopBrush, _pointRightWing);
g.DrawPolygon(pen, _pointBackWing);
g.DrawPolygon(pen, _pointLeftWing);
g.DrawPolygon(pen, _pointRightWing);
}
if (upgradeAirFighter.Rocket)
{
PointF[] _pointLeftRocket =
{
new PointF(_startPosX + 35, _startPosY),
new PointF(_startPosX + 45, _startPosY),
new PointF(_startPosX + 50, _startPosY + 3),
new PointF(_startPosX + 45, _startPosY + 5),
new PointF(_startPosX + 35, _startPosY + 5)
};
PointF[] _pointRightRocket =
{
new PointF(_startPosX + 35, _startPosY + 75),
new PointF(_startPosX + 45, _startPosY + 75),
new PointF(_startPosX + 50, _startPosY + 77),
new PointF(_startPosX + 45, _startPosY + 80),
new PointF(_startPosX + 35, _startPosY + 80)
};
g.FillPolygon(dopBrush, _pointLeftRocket);
g.FillPolygon(dopBrush, _pointRightRocket);
g.DrawPolygon(pen, _pointLeftRocket);
g.DrawPolygon(pen, _pointRightRocket);
}
}
}
}

View File

@ -9,7 +9,7 @@ namespace AirFighter
/// <summary>
/// Класс-сущность "Военный самолет"
/// </summary>
public class EntityAirFighter
internal class EntityAirFighter
{
/// <summary>
/// Скорость
@ -34,20 +34,12 @@ namespace AirFighter
/// <param name="weight"></param>
/// <param name="bodyColor"></param>
/// <returns></returns>
public EntityAirFighter(int speed, float weight, Color bodyColor)
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;
}
/// <summary>
/// Смена цвета
/// </summary>
/// <param name="color"></param>
public void ChangeColor(Color color)
{
BodyColor = color;
}
}
}

View File

@ -1,47 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirFighter
{
/// <summary>
/// Класс-сущность самолет разведчик
/// </summary>
internal class EntityUpgradeAirFighter : EntityAirFighter
{
/// <summary>
/// Дополнительный цвет
/// </summary>
public Color DopColor { get; private set; }
/// <summary>
/// Признак наличия дополнительных крыльев
/// </summary>
public bool DopWing { get; private set; }
/// <summary>
/// Признак наличия ракет
/// </summary>
public bool Rocket { get; private set; }
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed"></param>
/// <param name="weight"></param>
/// <param name="bodyColor"></param>
/// <param name="dopColor"></param>
/// <param name="dopWing"></param>
/// <param name="rocket"></param>
public EntityUpgradeAirFighter(int speed, float weight, Color bodyColor, Color dopColor, bool dopWing, bool rocket) :
base(speed,weight,bodyColor)
{
DopColor = dopColor;
DopWing = dopWing;
Rocket = rocket;
}
public void ChangeDopColor(Color color)
{
DopColor = color;
}
}
}

View File

@ -1,60 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirFighter
{
/// <summary>
/// Расширение для класса DrawningAirFighter
/// </summary>
internal static class ExtentionAirFighter
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public static DrawningAirFighter CreateDrawningCar(this string info)
{
string[] strs = info.Split(_separatorForObject);
if (strs.Length == 3)
{
return new DrawningAirFighter(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]));
}
if (strs.Length == 6)
{
return new DrawningUpgradeAirFighter(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]),
Color.FromName(strs[3]), Convert.ToBoolean(strs[4]),
Convert.ToBoolean(strs[5]));
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningCar"></param>
/// <returns></returns>
public static string GetDataForSave(this DrawningAirFighter drawningAirFighter)
{
var airFighter = drawningAirFighter.AirFighter;
var str =
$"{airFighter.Speed}{_separatorForObject}{airFighter.Weight}{_separatorForObject}{airFighter.BodyColor.Name}";
if (airFighter is not EntityUpgradeAirFighter upgradeAirFighter)
{
return str;
}
return
$"{str}{_separatorForObject}{upgradeAirFighter.DopColor.Name}{_separatorForObject}{upgradeAirFighter.DopWing}{_separatorForObject}{upgradeAirFighter.Rocket}";
}
}
}

View File

@ -38,8 +38,6 @@
this.buttonDown = new System.Windows.Forms.Button();
this.buttonLeft = new System.Windows.Forms.Button();
this.buttonRight = new System.Windows.Forms.Button();
this.buttonUpgrade = new System.Windows.Forms.Button();
this.buttonSelectAirFighter = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxAirFighter)).BeginInit();
this.statusStrip.SuspendLayout();
this.SuspendLayout();
@ -144,34 +142,11 @@
this.buttonRight.UseVisualStyleBackColor = true;
this.buttonRight.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonUpgrade
//
this.buttonUpgrade.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonUpgrade.Location = new System.Drawing.Point(148, 379);
this.buttonUpgrade.Name = "buttonUpgrade";
this.buttonUpgrade.Size = new System.Drawing.Size(127, 29);
this.buttonUpgrade.TabIndex = 7;
this.buttonUpgrade.Text = "Модификация";
this.buttonUpgrade.UseVisualStyleBackColor = true;
this.buttonUpgrade.Click += new System.EventHandler(this.ButtonUpgrade_Click);
//
// buttonSelectAirFighter
//
this.buttonSelectAirFighter.Location = new System.Drawing.Point(565, 379);
this.buttonSelectAirFighter.Name = "buttonSelectAirFighter";
this.buttonSelectAirFighter.Size = new System.Drawing.Size(94, 29);
this.buttonSelectAirFighter.TabIndex = 8;
this.buttonSelectAirFighter.Text = "Выбрать";
this.buttonSelectAirFighter.UseVisualStyleBackColor = true;
this.buttonSelectAirFighter.Click += new System.EventHandler(this.ButtonSelectAirFighter_Click);
//
// FormAirFighter
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.buttonSelectAirFighter);
this.Controls.Add(this.buttonUpgrade);
this.Controls.Add(this.buttonRight);
this.Controls.Add(this.buttonLeft);
this.Controls.Add(this.buttonDown);
@ -201,7 +176,5 @@
private Button buttonDown;
private Button buttonLeft;
private Button buttonRight;
private Button buttonUpgrade;
private Button buttonSelectAirFighter;
}
}

View File

@ -3,10 +3,6 @@ namespace AirFighter
public partial class FormAirFighter : Form
{
private DrawningAirFighter _airFighter;
/// <summary>
/// Âûáðàííûé îáúåêò
/// </summary>
public DrawningAirFighter SelectedAirFighter { get ; private set; }
public FormAirFighter()
{
InitializeComponent();
@ -22,32 +18,19 @@ namespace AirFighter
pictureBoxAirFighter.Image = bmp;
}
/// <summary>
/// Ìåòîä óñòàíîâêè äàííûõ
/// </summary>
private void SetData()
{
Random rnd = new Random();
_airFighter.SetPosition(rnd.Next(10, 100), rnd.Next(10, 100), pictureBoxAirFighter.Width, pictureBoxAirFighter.Height);
toolStripStatusLabelSpeed.Text = $"Ñêîðîñòü: {_airFighter.AirFighter?.Speed}";
toolStripStatusLabelWeight.Text = $"Âåñ: {_airFighter.AirFighter?.Weight}";
toolStripStatusLabelBodyColor.Text = $"Öâåò: {_airFighter.AirFighter?.BodyColor}";
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreate_Click(object sender, EventArgs e)
{
_airFighter = new DrawningAirFighter();
Random rnd = new Random();
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;
}
_airFighter = new DrawningAirFighter(rnd.Next(200, 500), rnd.Next(2000, 5000), color);
SetData();
_airFighter.Init(rnd.Next(200, 500), rnd.Next(2000, 5000), Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256)));
_airFighter.SetPosition(rnd.Next(10, 100), rnd.Next(10, 100), pictureBoxAirFighter.Width, pictureBoxAirFighter.Height);
toolStripStatusLabelSpeed.Text = $"Ñêîðîñòü: {_airFighter.AirFighter?.Speed}";
toolStripStatusLabelWeight.Text = $"Âåñ: {_airFighter.AirFighter?.Weight}";
toolStripStatusLabelBodyColor.Text = $"Öâåò: {_airFighter.AirFighter?.BodyColor}";
Draw();
}
/// <summary>
@ -85,36 +68,5 @@ namespace AirFighter
_airFighter?.ChangeBorders(pictureBoxAirFighter.Width, pictureBoxAirFighter.Height);
Draw();
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ìîäèôèêàöèÿ"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonUpgrade_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;
}
_airFighter = new DrawningUpgradeAirFighter(rnd.Next(300, 600), rnd.Next(2000, 5000), color,
dopColor, Convert.ToBoolean(rnd.Next(0, 2)), Convert.ToBoolean(rnd.Next(0, 2)));
SetData();
Draw();
}
private void ButtonSelectAirFighter_Click(object sender, EventArgs e)
{
SelectedAirFighter = _airFighter;
DialogResult = DialogResult.OK;
}
}
}

View File

@ -1,368 +0,0 @@
namespace AirFighter
{
partial class FormAirFighterConfig
{
/// <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.labelSimpleObject = new System.Windows.Forms.Label();
this.labelModifiedObject = new System.Windows.Forms.Label();
this.groupBoxColors = new System.Windows.Forms.GroupBox();
this.panelPurple = new System.Windows.Forms.Panel();
this.panelBlack = new System.Windows.Forms.Panel();
this.panelGray = new System.Windows.Forms.Panel();
this.panelWhite = new System.Windows.Forms.Panel();
this.panelYellow = new System.Windows.Forms.Panel();
this.panelBlue = new System.Windows.Forms.Panel();
this.panelGreen = new System.Windows.Forms.Panel();
this.panelRed = new System.Windows.Forms.Panel();
this.checkBoxDopWing = new System.Windows.Forms.CheckBox();
this.checkBoxRocket = 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.pictureBoxObject = new System.Windows.Forms.PictureBox();
this.panelObject = new System.Windows.Forms.Panel();
this.labelDopColor = new System.Windows.Forms.Label();
this.labelBaseColor = new System.Windows.Forms.Label();
this.buttonOk = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.groupBoxConfig.SuspendLayout();
this.groupBoxColors.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).BeginInit();
this.panelObject.SuspendLayout();
this.SuspendLayout();
//
// groupBoxConfig
//
this.groupBoxConfig.Controls.Add(this.labelSimpleObject);
this.groupBoxConfig.Controls.Add(this.labelModifiedObject);
this.groupBoxConfig.Controls.Add(this.groupBoxColors);
this.groupBoxConfig.Controls.Add(this.checkBoxDopWing);
this.groupBoxConfig.Controls.Add(this.checkBoxRocket);
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.Location = new System.Drawing.Point(0, 0);
this.groupBoxConfig.Name = "groupBoxConfig";
this.groupBoxConfig.Size = new System.Drawing.Size(602, 309);
this.groupBoxConfig.TabIndex = 0;
this.groupBoxConfig.TabStop = false;
this.groupBoxConfig.Text = "Параметры";
//
// labelSimpleObject
//
this.labelSimpleObject.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelSimpleObject.Location = new System.Drawing.Point(357, 196);
this.labelSimpleObject.Name = "labelSimpleObject";
this.labelSimpleObject.Size = new System.Drawing.Size(111, 50);
this.labelSimpleObject.TabIndex = 0;
this.labelSimpleObject.Text = "Простой";
this.labelSimpleObject.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelSimpleObject.MouseDown += new System.Windows.Forms.MouseEventHandler(this.LabelObject_MouseDown);
//
// labelModifiedObject
//
this.labelModifiedObject.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelModifiedObject.Location = new System.Drawing.Point(474, 196);
this.labelModifiedObject.Name = "labelModifiedObject";
this.labelModifiedObject.Size = new System.Drawing.Size(111, 50);
this.labelModifiedObject.TabIndex = 1;
this.labelModifiedObject.Text = "Продвинутый";
this.labelModifiedObject.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelModifiedObject.MouseDown += new System.Windows.Forms.MouseEventHandler(this.LabelObject_MouseDown);
//
// groupBoxColors
//
this.groupBoxColors.Controls.Add(this.panelPurple);
this.groupBoxColors.Controls.Add(this.panelBlack);
this.groupBoxColors.Controls.Add(this.panelGray);
this.groupBoxColors.Controls.Add(this.panelWhite);
this.groupBoxColors.Controls.Add(this.panelYellow);
this.groupBoxColors.Controls.Add(this.panelBlue);
this.groupBoxColors.Controls.Add(this.panelGreen);
this.groupBoxColors.Controls.Add(this.panelRed);
this.groupBoxColors.Location = new System.Drawing.Point(321, 12);
this.groupBoxColors.Name = "groupBoxColors";
this.groupBoxColors.Size = new System.Drawing.Size(264, 155);
this.groupBoxColors.TabIndex = 6;
this.groupBoxColors.TabStop = false;
this.groupBoxColors.Text = "Цвета";
//
// panelPurple
//
this.panelPurple.BackColor = System.Drawing.Color.Purple;
this.panelPurple.Location = new System.Drawing.Point(197, 87);
this.panelPurple.Name = "panelPurple";
this.panelPurple.Size = new System.Drawing.Size(53, 55);
this.panelPurple.TabIndex = 7;
this.panelPurple.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelBlack
//
this.panelBlack.BackColor = System.Drawing.Color.Black;
this.panelBlack.Location = new System.Drawing.Point(138, 87);
this.panelBlack.Name = "panelBlack";
this.panelBlack.Size = new System.Drawing.Size(53, 55);
this.panelBlack.TabIndex = 6;
this.panelBlack.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelGray
//
this.panelGray.BackColor = System.Drawing.Color.Gray;
this.panelGray.Location = new System.Drawing.Point(79, 87);
this.panelGray.Name = "panelGray";
this.panelGray.Size = new System.Drawing.Size(53, 55);
this.panelGray.TabIndex = 5;
this.panelGray.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelWhite
//
this.panelWhite.BackColor = System.Drawing.Color.White;
this.panelWhite.Location = new System.Drawing.Point(20, 87);
this.panelWhite.Name = "panelWhite";
this.panelWhite.Size = new System.Drawing.Size(53, 55);
this.panelWhite.TabIndex = 4;
this.panelWhite.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelYellow
//
this.panelYellow.BackColor = System.Drawing.Color.Yellow;
this.panelYellow.Location = new System.Drawing.Point(197, 26);
this.panelYellow.Name = "panelYellow";
this.panelYellow.Size = new System.Drawing.Size(53, 55);
this.panelYellow.TabIndex = 3;
this.panelYellow.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelBlue
//
this.panelBlue.BackColor = System.Drawing.Color.Blue;
this.panelBlue.Location = new System.Drawing.Point(138, 26);
this.panelBlue.Name = "panelBlue";
this.panelBlue.Size = new System.Drawing.Size(53, 55);
this.panelBlue.TabIndex = 2;
this.panelBlue.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelGreen
//
this.panelGreen.BackColor = System.Drawing.Color.Green;
this.panelGreen.Location = new System.Drawing.Point(79, 26);
this.panelGreen.Name = "panelGreen";
this.panelGreen.Size = new System.Drawing.Size(53, 55);
this.panelGreen.TabIndex = 1;
this.panelGreen.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// panelRed
//
this.panelRed.BackColor = System.Drawing.Color.Red;
this.panelRed.Location = new System.Drawing.Point(20, 26);
this.panelRed.Name = "panelRed";
this.panelRed.Size = new System.Drawing.Size(53, 55);
this.panelRed.TabIndex = 0;
this.panelRed.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PanelColor_MouseDown);
//
// checkBoxDopWing
//
this.checkBoxDopWing.AutoSize = true;
this.checkBoxDopWing.Location = new System.Drawing.Point(12, 196);
this.checkBoxDopWing.Name = "checkBoxDopWing";
this.checkBoxDopWing.Size = new System.Drawing.Size(339, 24);
this.checkBoxDopWing.TabIndex = 5;
this.checkBoxDopWing.Text = "Признак наличия дополнительных крыльев";
this.checkBoxDopWing.UseVisualStyleBackColor = true;
//
// checkBoxRocket
//
this.checkBoxRocket.AutoSize = true;
this.checkBoxRocket.Location = new System.Drawing.Point(12, 166);
this.checkBoxRocket.Name = "checkBoxRocket";
this.checkBoxRocket.Size = new System.Drawing.Size(196, 24);
this.checkBoxRocket.TabIndex = 4;
this.checkBoxRocket.Text = "Признак наличия ракет";
this.checkBoxRocket.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
this.numericUpDownWeight.Location = new System.Drawing.Point(118, 85);
this.numericUpDownWeight.Name = "numericUpDownWeight";
this.numericUpDownWeight.Size = new System.Drawing.Size(66, 27);
this.numericUpDownWeight.TabIndex = 3;
this.numericUpDownWeight.Value = new decimal(new int[] {
100,
0,
0,
0});
//
// numericUpDownSpeed
//
this.numericUpDownSpeed.Location = new System.Drawing.Point(118, 52);
this.numericUpDownSpeed.Name = "numericUpDownSpeed";
this.numericUpDownSpeed.Size = new System.Drawing.Size(66, 27);
this.numericUpDownSpeed.TabIndex = 2;
this.numericUpDownSpeed.Value = new decimal(new int[] {
100,
0,
0,
0});
//
// labelWeight
//
this.labelWeight.AutoSize = true;
this.labelWeight.Location = new System.Drawing.Point(62, 87);
this.labelWeight.Name = "labelWeight";
this.labelWeight.Size = new System.Drawing.Size(33, 20);
this.labelWeight.TabIndex = 1;
this.labelWeight.Text = "Вес";
//
// labelSpeed
//
this.labelSpeed.AutoSize = true;
this.labelSpeed.Location = new System.Drawing.Point(39, 52);
this.labelSpeed.Name = "labelSpeed";
this.labelSpeed.Size = new System.Drawing.Size(73, 20);
this.labelSpeed.TabIndex = 0;
this.labelSpeed.Text = "Скорость";
//
// pictureBoxObject
//
this.pictureBoxObject.Location = new System.Drawing.Point(38, 75);
this.pictureBoxObject.Name = "pictureBoxObject";
this.pictureBoxObject.Size = new System.Drawing.Size(267, 124);
this.pictureBoxObject.TabIndex = 1;
this.pictureBoxObject.TabStop = false;
//
// panelObject
//
this.panelObject.AllowDrop = true;
this.panelObject.Controls.Add(this.labelDopColor);
this.panelObject.Controls.Add(this.labelBaseColor);
this.panelObject.Controls.Add(this.pictureBoxObject);
this.panelObject.Location = new System.Drawing.Point(608, 12);
this.panelObject.Name = "panelObject";
this.panelObject.Size = new System.Drawing.Size(319, 234);
this.panelObject.TabIndex = 2;
this.panelObject.DragDrop += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragDrop);
this.panelObject.DragEnter += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragEnter);
//
// labelDopColor
//
this.labelDopColor.AllowDrop = true;
this.labelDopColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelDopColor.Location = new System.Drawing.Point(185, 26);
this.labelDopColor.Name = "labelDopColor";
this.labelDopColor.Size = new System.Drawing.Size(120, 41);
this.labelDopColor.TabIndex = 3;
this.labelDopColor.Text = "Доп. Цвет";
this.labelDopColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelDopColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.LabelDopColor_DragDrop);
this.labelDopColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.LabelColor_DragEnter);
//
// labelBaseColor
//
this.labelBaseColor.AllowDrop = true;
this.labelBaseColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelBaseColor.Location = new System.Drawing.Point(38, 26);
this.labelBaseColor.Name = "labelBaseColor";
this.labelBaseColor.Size = new System.Drawing.Size(127, 41);
this.labelBaseColor.TabIndex = 2;
this.labelBaseColor.Text = "Цвет";
this.labelBaseColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelBaseColor.DragDrop += new System.Windows.Forms.DragEventHandler(this.LabelBaseColor_DragDrop);
this.labelBaseColor.DragEnter += new System.Windows.Forms.DragEventHandler(this.LabelColor_DragEnter);
//
// buttonOk
//
this.buttonOk.Location = new System.Drawing.Point(646, 271);
this.buttonOk.Name = "buttonOk";
this.buttonOk.Size = new System.Drawing.Size(117, 38);
this.buttonOk.TabIndex = 7;
this.buttonOk.Text = "Добавить";
this.buttonOk.UseVisualStyleBackColor = true;
this.buttonOk.Click += new System.EventHandler(this.ButtonOk_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(778, 271);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(122, 38);
this.buttonCancel.TabIndex = 8;
this.buttonCancel.Text = "Отменить";
this.buttonCancel.UseVisualStyleBackColor = true;
//
// FormAirFighterConfig
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(934, 316);
this.Controls.Add(this.buttonOk);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.panelObject);
this.Controls.Add(this.groupBoxConfig);
this.Name = "FormAirFighterConfig";
this.Text = "Создание объекта";
this.groupBoxConfig.ResumeLayout(false);
this.groupBoxConfig.PerformLayout();
this.groupBoxColors.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxObject)).EndInit();
this.panelObject.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private GroupBox groupBoxConfig;
private CheckBox checkBoxDopWing;
private CheckBox checkBoxRocket;
private NumericUpDown numericUpDownWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelWeight;
private Label labelSpeed;
private Label labelSimpleObject;
private Label labelModifiedObject;
private GroupBox groupBoxColors;
private Panel panelPurple;
private Panel panelBlack;
private Panel panelGray;
private Panel panelWhite;
private Panel panelYellow;
private Panel panelBlue;
private Panel panelGreen;
private Panel panelRed;
private PictureBox pictureBoxObject;
private Panel panelObject;
private Label labelDopColor;
private Label labelBaseColor;
private Button buttonOk;
private Button buttonCancel;
}
}

View File

@ -1,178 +0,0 @@
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 AirFighter
{
public partial class FormAirFighterConfig : Form
{
/// <summary>
/// Переменная-выбранный самолет
/// </summary>
DrawningAirFighter _airFighter = null;
/// <summary>
/// Событие
/// </summary>
private event Action<DrawningAirFighter> EventAddAirFighter;
/// <summary>
/// Конструктор
/// </summary>
public FormAirFighterConfig()
{
InitializeComponent();
panelBlack.MouseDown += PanelColor_MouseDown;
panelPurple.MouseDown += PanelColor_MouseDown;
panelGray.MouseDown += PanelColor_MouseDown;
panelGreen.MouseDown += PanelColor_MouseDown;
panelRed.MouseDown += PanelColor_MouseDown;
panelWhite.MouseDown += PanelColor_MouseDown;
panelYellow.MouseDown += PanelColor_MouseDown;
panelBlue.MouseDown += PanelColor_MouseDown;
// Закрытие формы
buttonCancel.Click += (object sender, EventArgs e) => this.Close();
}
/// <summary>
/// Отрисовать объект
/// </summary>
private void DrawAirFighter()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_airFighter?.SetPosition(5, 5, pictureBoxObject.Width, pictureBoxObject.Height);
_airFighter?.DrawAirFighter(gr);
pictureBoxObject.Image = bmp;
}
/// <summary>
/// Добавление события
/// </summary>
/// <param name="ev"></param>
public void AddEvent(Action<DrawningAirFighter> ev)
{
if (EventAddAirFighter == null)
{
EventAddAirFighter = new Action<DrawningAirFighter>(ev);
}
else
{
EventAddAirFighter += 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 "labelSimpleObject":
_airFighter = new DrawningAirFighter((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value, Color.White);
break;
case "labelModifiedObject":
_airFighter = new DrawningUpgradeAirFighter((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value, Color.White, Color.Black,
checkBoxRocket.Checked, checkBoxDopWing.Checked);
break;
}
DrawAirFighter();
}
/// <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_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
/// <summary>
/// Принимаем основной цвет
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelBaseColor_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)) && _airFighter != null)
{
_airFighter.AirFighter.ChangeColor((Color)e.Data.GetData(typeof(Color)));
DrawAirFighter();
}
}
/// <summary>
/// Принимаем дополнительный цвет
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LabelDopColor_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)) && _airFighter != null)
{
if (_airFighter is DrawningUpgradeAirFighter _upgradeAirFighter)
{
if (_upgradeAirFighter.AirFighter is EntityUpgradeAirFighter _entityUpgradeAirFighter)
{
_entityUpgradeAirFighter.ChangeDopColor((Color)e.Data.GetData(typeof(Color)));
DrawAirFighter();
}
}
}
}
/// <summary>
/// Добавление самолета
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonOk_Click(object sender, EventArgs e)
{
EventAddAirFighter?.Invoke(_airFighter);
Close();
}
}
}

View File

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

View File

@ -1,364 +0,0 @@
namespace AirFighter
{
partial class FormMapWithSetAirFighters
{
/// <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.groupBox = new System.Windows.Forms.GroupBox();
this.groupBoxMaps = new System.Windows.Forms.GroupBox();
this.buttonDeleteMap = new System.Windows.Forms.Button();
this.listBoxMaps = new System.Windows.Forms.ListBox();
this.buttonAddMap = new System.Windows.Forms.Button();
this.textBoxNewMapName = new System.Windows.Forms.TextBox();
this.comboBoxSelectorMap = new System.Windows.Forms.ComboBox();
this.buttonUp = new System.Windows.Forms.Button();
this.buttonDown = new System.Windows.Forms.Button();
this.buttonLeft = new System.Windows.Forms.Button();
this.buttonRight = new System.Windows.Forms.Button();
this.buttonShowOnMap = new System.Windows.Forms.Button();
this.buttonShowStorage = new System.Windows.Forms.Button();
this.buttonRemoveAirFighter = new System.Windows.Forms.Button();
this.maskedTextBoxPosition = new System.Windows.Forms.MaskedTextBox();
this.buttonAddAirFighter = new System.Windows.Forms.Button();
this.pictureBox = new System.Windows.Forms.PictureBox();
this.menuStrip = new System.Windows.Forms.MenuStrip();
this.FileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.SaveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.LoadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.buttonSortByType = new System.Windows.Forms.Button();
this.buttonSortByColor = new System.Windows.Forms.Button();
this.groupBox.SuspendLayout();
this.groupBoxMaps.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
this.menuStrip.SuspendLayout();
this.SuspendLayout();
//
// groupBox
//
this.groupBox.Controls.Add(this.buttonSortByColor);
this.groupBox.Controls.Add(this.buttonSortByType);
this.groupBox.Controls.Add(this.groupBoxMaps);
this.groupBox.Controls.Add(this.buttonUp);
this.groupBox.Controls.Add(this.buttonDown);
this.groupBox.Controls.Add(this.buttonLeft);
this.groupBox.Controls.Add(this.buttonRight);
this.groupBox.Controls.Add(this.buttonShowOnMap);
this.groupBox.Controls.Add(this.buttonShowStorage);
this.groupBox.Controls.Add(this.buttonRemoveAirFighter);
this.groupBox.Controls.Add(this.maskedTextBoxPosition);
this.groupBox.Controls.Add(this.buttonAddAirFighter);
this.groupBox.Dock = System.Windows.Forms.DockStyle.Right;
this.groupBox.Location = new System.Drawing.Point(732, 28);
this.groupBox.Name = "groupBox";
this.groupBox.Size = new System.Drawing.Size(250, 638);
this.groupBox.TabIndex = 0;
this.groupBox.TabStop = false;
this.groupBox.Text = "Инструменты";
//
// groupBoxMaps
//
this.groupBoxMaps.Controls.Add(this.buttonDeleteMap);
this.groupBoxMaps.Controls.Add(this.listBoxMaps);
this.groupBoxMaps.Controls.Add(this.buttonAddMap);
this.groupBoxMaps.Controls.Add(this.textBoxNewMapName);
this.groupBoxMaps.Controls.Add(this.comboBoxSelectorMap);
this.groupBoxMaps.Location = new System.Drawing.Point(0, 12);
this.groupBoxMaps.Name = "groupBoxMaps";
this.groupBoxMaps.Size = new System.Drawing.Size(250, 278);
this.groupBoxMaps.TabIndex = 6;
this.groupBoxMaps.TabStop = false;
this.groupBoxMaps.Text = "Карты";
//
// buttonDeleteMap
//
this.buttonDeleteMap.Location = new System.Drawing.Point(17, 244);
this.buttonDeleteMap.Name = "buttonDeleteMap";
this.buttonDeleteMap.Size = new System.Drawing.Size(210, 29);
this.buttonDeleteMap.TabIndex = 4;
this.buttonDeleteMap.Text = "Удалить карту";
this.buttonDeleteMap.UseVisualStyleBackColor = true;
this.buttonDeleteMap.Click += new System.EventHandler(this.ButtonDeleteMap_Click);
//
// listBoxMaps
//
this.listBoxMaps.FormattingEnabled = true;
this.listBoxMaps.ItemHeight = 20;
this.listBoxMaps.Location = new System.Drawing.Point(17, 154);
this.listBoxMaps.Name = "listBoxMaps";
this.listBoxMaps.Size = new System.Drawing.Size(210, 84);
this.listBoxMaps.TabIndex = 3;
this.listBoxMaps.SelectedIndexChanged += new System.EventHandler(this.ListBoxMaps_SelectedIndexChanged);
//
// buttonAddMap
//
this.buttonAddMap.Location = new System.Drawing.Point(17, 119);
this.buttonAddMap.Name = "buttonAddMap";
this.buttonAddMap.Size = new System.Drawing.Size(210, 29);
this.buttonAddMap.TabIndex = 2;
this.buttonAddMap.Text = "Добавить карту";
this.buttonAddMap.UseVisualStyleBackColor = true;
this.buttonAddMap.Click += new System.EventHandler(this.ButtonAddMap_Click);
//
// textBoxNewMapName
//
this.textBoxNewMapName.Location = new System.Drawing.Point(17, 36);
this.textBoxNewMapName.Name = "textBoxNewMapName";
this.textBoxNewMapName.Size = new System.Drawing.Size(210, 27);
this.textBoxNewMapName.TabIndex = 1;
//
// 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(17, 75);
this.comboBoxSelectorMap.Name = "comboBoxSelectorMap";
this.comboBoxSelectorMap.Size = new System.Drawing.Size(210, 28);
this.comboBoxSelectorMap.TabIndex = 0;
//
// buttonUp
//
this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonUp.BackgroundImage = global::AirFighter.Properties.Resources.Up;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonUp.Location = new System.Drawing.Point(135, 558);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(30, 30);
this.buttonUp.TabIndex = 2;
this.buttonUp.UseVisualStyleBackColor = true;
this.buttonUp.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonDown
//
this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDown.BackgroundImage = global::AirFighter.Properties.Resources.Down;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonDown.Location = new System.Drawing.Point(135, 596);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(30, 30);
this.buttonDown.TabIndex = 3;
this.buttonDown.UseVisualStyleBackColor = true;
this.buttonDown.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonLeft
//
this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonLeft.BackgroundImage = global::AirFighter.Properties.Resources.Left;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonLeft.Location = new System.Drawing.Point(99, 596);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(30, 30);
this.buttonLeft.TabIndex = 4;
this.buttonLeft.UseVisualStyleBackColor = true;
this.buttonLeft.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonRight
//
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::AirFighter.Properties.Resources.Right;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonRight.Location = new System.Drawing.Point(171, 596);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(30, 30);
this.buttonRight.TabIndex = 5;
this.buttonRight.UseVisualStyleBackColor = true;
this.buttonRight.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonShowOnMap
//
this.buttonShowOnMap.Location = new System.Drawing.Point(17, 522);
this.buttonShowOnMap.Name = "buttonShowOnMap";
this.buttonShowOnMap.Size = new System.Drawing.Size(210, 29);
this.buttonShowOnMap.TabIndex = 5;
this.buttonShowOnMap.Text = "Посмотреть карту";
this.buttonShowOnMap.UseVisualStyleBackColor = true;
this.buttonShowOnMap.Click += new System.EventHandler(this.ButtonShowOnMap_Click);
//
// buttonShowStorage
//
this.buttonShowStorage.Location = new System.Drawing.Point(17, 487);
this.buttonShowStorage.Name = "buttonShowStorage";
this.buttonShowStorage.Size = new System.Drawing.Size(210, 29);
this.buttonShowStorage.TabIndex = 4;
this.buttonShowStorage.Text = "Посмотреть хранилище";
this.buttonShowStorage.UseVisualStyleBackColor = true;
this.buttonShowStorage.Click += new System.EventHandler(this.ButtonShowStorage_Click);
//
// buttonRemoveAirFighter
//
this.buttonRemoveAirFighter.Location = new System.Drawing.Point(17, 452);
this.buttonRemoveAirFighter.Name = "buttonRemoveAirFighter";
this.buttonRemoveAirFighter.Size = new System.Drawing.Size(210, 29);
this.buttonRemoveAirFighter.TabIndex = 3;
this.buttonRemoveAirFighter.Text = "Удалить самолет";
this.buttonRemoveAirFighter.UseVisualStyleBackColor = true;
this.buttonRemoveAirFighter.Click += new System.EventHandler(this.ButtonRemoveAirFighter_Click);
//
// maskedTextBoxPosition
//
this.maskedTextBoxPosition.Location = new System.Drawing.Point(17, 419);
this.maskedTextBoxPosition.Mask = "00";
this.maskedTextBoxPosition.Name = "maskedTextBoxPosition";
this.maskedTextBoxPosition.Size = new System.Drawing.Size(210, 27);
this.maskedTextBoxPosition.TabIndex = 2;
//
// buttonAddAirFighter
//
this.buttonAddAirFighter.Location = new System.Drawing.Point(17, 375);
this.buttonAddAirFighter.Name = "buttonAddAirFighter";
this.buttonAddAirFighter.Size = new System.Drawing.Size(210, 29);
this.buttonAddAirFighter.TabIndex = 1;
this.buttonAddAirFighter.Text = "Добавить самолет";
this.buttonAddAirFighter.UseVisualStyleBackColor = true;
this.buttonAddAirFighter.Click += new System.EventHandler(this.ButtonAddAirFighter_Click);
//
// pictureBox
//
this.pictureBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBox.Location = new System.Drawing.Point(0, 28);
this.pictureBox.Name = "pictureBox";
this.pictureBox.Size = new System.Drawing.Size(732, 638);
this.pictureBox.TabIndex = 1;
this.pictureBox.TabStop = false;
//
// menuStrip
//
this.menuStrip.ImageScalingSize = new System.Drawing.Size(20, 20);
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.FileToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(982, 28);
this.menuStrip.TabIndex = 2;
//
// FileToolStripMenuItem
//
this.FileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.SaveToolStripMenuItem,
this.LoadToolStripMenuItem});
this.FileToolStripMenuItem.Name = "FileToolStripMenuItem";
this.FileToolStripMenuItem.Size = new System.Drawing.Size(59, 24);
this.FileToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(177, 26);
this.SaveToolStripMenuItem.Text = "Сохранение";
this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// LoadToolStripMenuItem
//
this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(177, 26);
this.LoadToolStripMenuItem.Text = "Загрузка";
this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
// openFileDialog
//
this.openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
this.saveFileDialog.Filter = "txt file | *.txt";
//
// buttonSortByType
//
this.buttonSortByType.Location = new System.Drawing.Point(17, 296);
this.buttonSortByType.Name = "buttonSortByType";
this.buttonSortByType.Size = new System.Drawing.Size(210, 29);
this.buttonSortByType.TabIndex = 7;
this.buttonSortByType.Text = "Сортировать по типу";
this.buttonSortByType.UseVisualStyleBackColor = true;
this.buttonSortByType.Click += new System.EventHandler(this.ButtonSortByType_Click);
//
// buttonSortByColor
//
this.buttonSortByColor.Location = new System.Drawing.Point(17, 331);
this.buttonSortByColor.Name = "buttonSortByColor";
this.buttonSortByColor.Size = new System.Drawing.Size(210, 29);
this.buttonSortByColor.TabIndex = 8;
this.buttonSortByColor.Text = "Сортировать по цвету";
this.buttonSortByColor.UseVisualStyleBackColor = true;
this.buttonSortByColor.Click += new System.EventHandler(this.ButtonSortByColor_Click);
//
// FormMapWithSetAirFighters
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(982, 666);
this.Controls.Add(this.pictureBox);
this.Controls.Add(this.groupBox);
this.Controls.Add(this.menuStrip);
this.MainMenuStrip = this.menuStrip;
this.Name = "FormMapWithSetAirFighters";
this.Text = "FormMapWithSetAirFighters";
this.groupBox.ResumeLayout(false);
this.groupBox.PerformLayout();
this.groupBoxMaps.ResumeLayout(false);
this.groupBoxMaps.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private GroupBox groupBox;
private Button buttonShowOnMap;
private Button buttonShowStorage;
private Button buttonRemoveAirFighter;
private MaskedTextBox maskedTextBoxPosition;
private Button buttonAddAirFighter;
private ComboBox comboBoxSelectorMap;
private PictureBox pictureBox;
private Button buttonUp;
private Button buttonDown;
private Button buttonLeft;
private Button buttonRight;
private GroupBox groupBoxMaps;
private Button buttonDeleteMap;
private ListBox listBoxMaps;
private Button buttonAddMap;
private TextBox textBoxNewMapName;
private MenuStrip menuStrip;
private ToolStripMenuItem FileToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@ -1,352 +0,0 @@
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;
using static System.Windows.Forms.DataFormats;
namespace AirFighter
{
public partial class FormMapWithSetAirFighters : Form
{
/// <summary>
/// Словарь для выпадающего списка
/// </summary>
private readonly Dictionary<string, AbstractMap> _mapsDict = new()
{
{ "Простая карта", new SimpleMap() },
{ "Карта шторма", new StormMap() }
};
/// <summary>
/// Объект от коллекции карт
/// </summary>
private readonly MapsCollection _mapsCollection;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
public FormMapWithSetAirFighters(ILogger<FormMapWithSetAirFighters> logger)
{
InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.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;
}
}
void AddAirFighter(DrawningAirFighter _airFighter)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
if (_airFighter != null)
{
DrawningObjectAirFighter airFighter = new(_airFighter);
try
{
if ((_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + airFighter) == 0)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation($"Добавлен объект {airFighter}");
}
else
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogInformation($"Не удалось добавить объект {airFighter}");
}
}
catch (StorageOverflowException ex)
{
MessageBox.Show($"Ошибка добавления: {ex.Message}");
_logger.LogWarning($"Ошибка переполнения хранилища: {ex.Message}");
}
catch (Exception ex)
{
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
_logger.LogWarning($"Неизвестная ошибка: {ex.Message}");
}
}
}
/// <summary>
/// Добавление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddAirFighter_Click(object sender, EventArgs e)
{
var formAirFighterConfig = new FormAirFighterConfig();
Action<DrawningAirFighter> airFighterDelegate;
airFighterDelegate = new(AddAirFighter);
formAirFighterConfig.AddEvent(airFighterDelegate);
formAirFighterConfig.Show();
}
/// <summary>
/// Удаление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveAirFighter_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text))
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
try
{
var deletedObject = (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos);
if (deletedObject != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation($"Удаление объекта {deletedObject}");
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogInformation($"Не удалось удалить объект {deletedObject}");
}
}catch(AirFighterNotFoundException ex)
{
MessageBox.Show($"Ошибка удаления: {ex.Message}");
_logger.LogWarning($"Ошибка, объект не найден: {ex.Message}");
}
catch(Exception ex)
{
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
_logger.LogWarning($"Неизвестная ошибка: {ex.Message}");
}
}
/// <summary>
/// Вывод набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonShowStorage_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
/// <summary>
/// Вывод карты
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonShowOnMap_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
pictureBox.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 (listBoxMaps.SelectedIndex == -1)
{
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;
}
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].MoveObject(dir);
}
/// <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);
return;
}
if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text))
{
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
_mapsCollection.AddMap(textBoxNewMapName.Text,
_mapsDict[comboBoxSelectorMap.Text]);
_logger.LogInformation($"Добавлена карта: {textBoxNewMapName.Text}");
ReloadMaps();
}
/// <summary>
/// Выбор карты
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation($"Осуществлен переход на карту {listBoxMaps.SelectedItem?.ToString() ?? string.Empty}");
}
/// <summary>
/// Удаление карты
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonDeleteMap_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps();
_logger.LogInformation($"Удалена карта {listBoxMaps.SelectedItem}");
}
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></par
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.LogInformation($"Сохранение в файл {saveFileDialog.FileName} прошло успешно");
}
catch(Exception ex)
{
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не удалось сохранить в файл. Ошибка: {ex.Message}");
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_mapsCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Загрузка из файла {openFileDialog.FileName} прошла успешна");
ReloadMaps();
}
catch(Exception ex)
{
MessageBox.Show($"Загрузка не удалась: {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не удалось загрузить из файла. Ошибка: {ex.Message}");
}
}
}
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByType_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
_mapsCollection[listBoxMaps.SelectedItem?.ToString() ??
string.Empty].Sort(new AirFighterCompareByType());
pictureBox.Image =
_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
_mapsCollection[listBoxMaps.SelectedItem?.ToString() ??
string.Empty].Sort(new AirFighterCompareByColor());
pictureBox.Image =
_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
}
}

View File

@ -1,72 +0,0 @@
<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>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>144, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>311, 17</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>25</value>
</metadata>
</root>

View File

@ -1,48 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirFighter
{
/// <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>
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

@ -1,233 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirFighter
{
/// <summary>
/// Карта с набром объектов под нее
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
internal class MapWithSetAirFightersGeneric<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 SetAirFightersGeneric<T> _setAirFighters;
/// <summary>
/// Карта
/// </summary>
private readonly U _map;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
/// <param name="map"></param>
public MapWithSetAirFightersGeneric(int picWidth, int picHeight, U map)
{
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_setAirFighters = new SetAirFightersGeneric<T>(width * height);
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_map = map;
}
/// <summary>
/// Перегрузка оператора сложения
/// </summary>
/// <param name="map"></param>
/// <param name="car"></param>
/// <returns></returns>
public static int operator +(MapWithSetAirFightersGeneric<T, U> map, T airFighter)
{
return map._setAirFighters.Insert(airFighter);
}
/// <summary>
/// Перегрузка оператора вычитания
/// </summary>
/// <param name="map"></param>
/// <param name="position"></param>
/// <returns></returns>
public static T operator -(MapWithSetAirFightersGeneric<T, U> map, int
position)
{
return map._setAirFighters.Remove(position);
}
/// <summary>
/// Вывод всего набора объектов
/// </summary>
/// <returns></returns>
public Bitmap ShowSet()
{
Bitmap bmp = new(_pictureWidth, _pictureHeight);
Graphics gr = Graphics.FromImage(bmp);
DrawBackground(gr);
DrawAirFighters(gr);
return bmp;
}
/// <summary>
/// Просмотр объекта на карте
/// </summary>
/// <returns></returns>
public Bitmap ShowOnMap()
{
Shaking();
foreach (var airFighter in _setAirFighters.GetAirFighters())
{
return _map.CreateMap(_pictureWidth, _pictureHeight, airFighter);
}
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 airFighter in _setAirFighters.GetAirFighters())
{
data += $"{airFighter.GetInfo()}{separatorData}";
}
return data;
}
/// <summary>
/// Загрузка списка из массива строк
/// </summary>
/// <param name="records"></param>
public void LoadData(string[] records)
{
foreach (var rec in records)
{
_setAirFighters.Insert(DrawningObjectAirFighter.Create(rec) as T);
}
}
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer"></param>
public void Sort(IComparer<T> comparer)
{
_setAirFighters.SortSet(comparer);
}
/// <summary>
/// "Взбалтываем" набор, чтобы все элементы оказались в начале
/// </summary>
private void Shaking()
{
int j = _setAirFighters.Count - 1;
for (int i = 0; i < _setAirFighters.Count; i++)
{
if (_setAirFighters[i] == null)
{
for (; j > i; j--)
{
var airFighter = _setAirFighters[j];
if (airFighter != null)
{
_setAirFighters.Insert(airFighter, i);
_setAirFighters.Remove(j);
break;
}
}
if (j <= i)
{
return;
}
}
}
}
/// <summary>
/// Метод отрисовки фона
/// </summary>
/// <param name="g"></param>
private void DrawBackground(Graphics g)
{
Pen pen = new(Color.Black, 3);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j)
{//линия рамзетки места
g.DrawLine(pen, i * _placeSizeWidth, j * _placeSizeHeight, i *
_placeSizeWidth + _placeSizeWidth / 2, j * _placeSizeHeight);
g.FillPolygon(new SolidBrush(Color.Gray), new PointF[]
{
new Point(i * _placeSizeWidth + _placeSizeWidth / 5, j * _placeSizeHeight + _placeSizeHeight / 10),
new Point((i + 1) * _placeSizeWidth - _placeSizeWidth / 5, j * _placeSizeHeight + _placeSizeHeight / 10),
new Point((i + 1) * _placeSizeWidth - _placeSizeWidth / 5, (j + 1) * _placeSizeHeight - _placeSizeHeight / 10),
new Point(i * _placeSizeWidth + _placeSizeWidth / 5, (j + 1) * _placeSizeHeight - _placeSizeHeight / 10),
});
}
g.DrawLine(pen, i * _placeSizeWidth, 0, i * _placeSizeWidth,
(_pictureHeight / _placeSizeHeight) * _placeSizeHeight);
}
}
/// <summary>
/// Метод прорисовки объектов
/// </summary>
/// <param name="g"></param>
private void DrawAirFighters(Graphics g)
{
int currentWidth = _pictureWidth / _placeSizeWidth - 1;
int currentHeight = _pictureHeight / _placeSizeHeight - 1;
foreach (var airFighter in _setAirFighters.GetAirFighters())
{
airFighter?.SetObject(currentWidth * _placeSizeWidth + 50, currentHeight * _placeSizeHeight + 10, _pictureWidth, _pictureHeight);
airFighter?.DrawningObject(g);
if (currentWidth > 0)
{
currentWidth -= 1;
}
else
{
if (currentHeight > 0)
{
currentHeight -= 1;
currentWidth = _pictureWidth / _placeSizeWidth - 1;
}
else return;
}
}
}
}
}

View File

@ -1,154 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirFighter
{
/// <summary>
/// Класс для хранения коллекции карт
/// </summary>
internal class MapsCollection
{
/// <summary>
/// Словарь (хранилище) с картами
/// </summary>
readonly Dictionary<string, MapWithSetAirFightersGeneric<IDrawningObject, AbstractMap>> _mapStorages;
/// <summary>
/// Возвращение списка названий карт
/// </summary>
public List<string> Keys => _mapStorages.Keys.ToList();
/// <summary>
/// Ширина окна отрисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Разделитель для записи информации по элементу словаря в файл
/// </summary>
private readonly char separatorDict = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char separatorData = ';';
/// <summary>
/// Высота окна отрисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="pictureWidth"></param>
/// <param name="pictureHeight"></param>
public MapsCollection(int pictureWidth, int pictureHeight)
{
_mapStorages = new Dictionary<string, MapWithSetAirFightersGeneric<IDrawningObject, AbstractMap>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
/// <summary>
/// Добавление карты
/// </summary>
/// <param name="name">Название карты</param>
/// <param name="map">Карта</param>
public void AddMap(string name, AbstractMap map)
{
if (!string.IsNullOrEmpty(name) && map != null && !Keys.Contains(name))
{
_mapStorages.Add(name, new MapWithSetAirFightersGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
}
}
/// <summary>
/// Удаление карты
/// </summary>
/// <param name="name">Название карты</param>
public void DelMap(string name)
{
if (!string.IsNullOrEmpty(name))
{
_mapStorages.Remove(name);
}
}
/// <summary>
/// Доступ к парковке
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public MapWithSetAirFightersGeneric<IDrawningObject, AbstractMap> this[string ind]
{
get
{
MapWithSetAirFightersGeneric<IDrawningObject, AbstractMap> _map;
if (_mapStorages.TryGetValue(ind, out _map))
{
return _map;
}
else
return null;
}
}
/// <summary>
/// Сохранение информации по самолетам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns></returns>
public bool SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter sw = new(filename))
{
sw.Write($"MapsCollection{Environment.NewLine}");
foreach (var storage in _mapStorages)
{
sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}");
}
}
return true;
}
/// <summary>
/// Загрузка нформации по самолетам на парковках из файла
/// </summary>
/// <param name = "filename" ></ param >
/// < returns ></ returns >
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не найден");
}
string bufferTextFromFile = "";
using (StreamReader sr = new(filename))
{
string checkMap = sr.ReadLine();
if (!checkMap.Contains("MapsCollection"))
{
throw new FileFormatException("Формат данных в файле не правильный");
}
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 "StormMap":
map = new StormMap();
break;
}
_mapStorages.Add(strs[0], new MapWithSetAirFightersGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[strs[0]].LoadData(strs[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
bufferTextFromFile = sr.ReadLine();
}
}
}
}
}

View File

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

View File

@ -1,146 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms.VisualStyles;
namespace AirFighter
{
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T"></typeparam>
internal class SetAirFightersGeneric<T>
where T: class, IEquatable<T>
{
/// <summary>
/// Список объектов, которые храним
/// </summary>
private readonly List<T> _places;
/// <summary>
/// Количество объектов в списке
/// </summary>
public int Count => _places.Count;
/// <summary>
/// Максимальная длина списка
/// </summary>
private readonly int _maxCount;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetAirFightersGeneric(int count)
{
_places = new List<T>();
_maxCount = count;
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="airFighter">Добавляемый автомобиль</param>
/// <returns></returns>
public int Insert(T airFighter)
{
return Insert(airFighter, 0);
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="airFighter">Добавляемый автомобиль</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public int Insert(T airFighter, int position)
{
if (_places.Contains(airFighter))
{
throw new ArgumentException("Элемент с такими характеристиками существует в хранилище");
}
if (Count >= _maxCount)
{
throw new StorageOverflowException();
}
if (position < 0 && position > _maxCount)
{
return -1;
}
else
{
_places.Insert(position, airFighter);
return position;
}
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T Remove(int position)
{
if (position >= 0 && position < Count)
{
T temp = _places[position];
_places.RemoveAt(position);
return temp;
}
else
{
throw new AirFighterNotFoundException(position);
}
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T this[int position]
{
get
{
if (position >= 0 && position < _maxCount)
{
return _places[position];
}
else
return null;
}
set
{
if (position >= 0 && position < _maxCount)
{
_places.Insert(position, value);
}
}
}
/// <summary>
/// Проход по набору до первого пустого
/// </summary>
/// <returns></returns>
public IEnumerable<T> GetAirFighters()
{
foreach (var airFighter in _places)
{
if (airFighter != null)
{
yield return airFighter;
}
else
{
yield break;
}
}
}
/// <summary>
/// Сортировка набора объектов
/// </summary>
/// <param name="comparer"></param>
public void SortSet(IComparer<T> comparer)
{
if (comparer == null)
{
return;
}
_places.Sort(comparer);
}
}
}

View File

@ -1,53 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirFighter
{
internal class SimpleMap : AbstractMap
{
/// <summary>
/// Цвет участка закрытого
/// </summary>
private readonly Brush barrierColor = new SolidBrush(Color.Gray);
/// <summary>
/// Цвет участка открытого
/// </summary>
private readonly Brush roadColor = new SolidBrush(Color.LightBlue);
protected override void DrawBarrierPart(Graphics g, int i, int j)
{
g.FillRectangle(barrierColor, i * _size_x, j * _size_y, (i + 1) * _size_x, (j + 1) * _size_y);
}
protected override void DrawRoadPart(Graphics g, int i, int j)
{
g.FillRectangle(roadColor, i * _size_x, j * _size_y, (i + 1) * _size_x, (j + 1) * _size_y);
}
protected override void GenerateMap()
{
_map = new int[100, 100];
_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, 100);
int y = _random.Next(0, 100);
if (_map[x, y] == _freeRoad)
{
_map[x, y] = _barrier;
counter++;
}
}
}
}
}

View File

@ -1,21 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace AirFighter
{
[Serializable]
internal class StorageOverflowException : ApplicationException
{
public StorageOverflowException(int count) : base($"В наборе превышено допустимое количество: { count}") { }
public StorageOverflowException() : base() { }
public StorageOverflowException(string message) : base(message) { }
public StorageOverflowException(string message, Exception exception) :
base(message, exception)
{ }
protected StorageOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -1,66 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirFighter
{
internal class StormMap : AbstractMap
{
/// <summary>
/// Цвет участка закрытого
/// </summary>
private readonly Brush barrierColor = new SolidBrush(Color.Black);
/// <summary>
/// Цвет участка открытого
/// </summary>
private readonly Brush roadColor = new SolidBrush(Color.FromArgb(168, 168, 168));
/// <summary>
/// Дополнительный цвет открытого участка
/// </summary>
private readonly Brush dopRoadColor = new SolidBrush(Color.LightGray);
protected override void DrawBarrierPart(Graphics g, int i, int j)
{
g.FillRectangle(barrierColor, i * _size_x, j * _size_y, (i + 1) * _size_x, (j + 1) * _size_y);
}
protected override void DrawRoadPart(Graphics g, int i, int j)
{
Random random = new Random();
if (random.Next(0, 2) == 1)
{
g.FillRectangle(roadColor, i * _size_x, j * _size_y, (i + 1) * _size_x, (j + 1) * _size_y);
}
else
{
g.FillRectangle(dopRoadColor, i * _size_x, j * _size_y, (i + 1) * _size_x, (j + 1) * _size_y);
}
}
protected override void GenerateMap()
{
_map = new int[100, 100];
_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, 100);
int y = _random.Next(0, 100);
if (_map[x, y] == _freeRoad)
{
_map[x, y] = _barrier;
counter++;
}
}
}
}
}

View File

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