Compare commits

...

10 Commits
main ... lab7

38 changed files with 3062 additions and 79 deletions

View File

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

View File

@ -8,4 +8,50 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="DependencyInjection.AutoRegistration" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="8.0.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyModel" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.FileProviders.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.FileProviders.Physical" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.FileSystemGlobbing" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Options" Version="8.0.1" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Primitives" Version="8.0.0" />
<PackageReference Include="NLog" Version="5.2.8" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
<PackageReference Include="System.Reflection.TypeExtensions" Version="4.7.0" />
<PackageReference Include="System.Runtime.CompilerServices.Unsafe" Version="6.0.0" />
<PackageReference Include="System.Text.Encodings.Web" Version="8.0.0" />
<PackageReference Include="System.Text.Json" Version="8.0.1" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
</Project>

View File

@ -0,0 +1,12 @@
using System;
namespace AirBomber
{
public enum DirectionType
{
Up = 1,
Down = 2,
Left = 3,
Right = 4
}
}

View File

@ -0,0 +1,135 @@
using AirBomber.Entities;
using System;
namespace AirBomber.DrawingObjects
{
internal class DrawingAirBomber : DrawingWarAirplane
{
public DrawingAirBomber(int speed, float weight, Color bodyColor, Color additionalColor, bool fuelTank,
bool bombs, int width, int height) : base(speed, weight, bodyColor, width, height, 110, 100)
{
if(EntityWarAirplane != null)
{
EntityWarAirplane = new EntityAirBomber(speed, weight, bodyColor, additionalColor, fuelTank, bombs);
}
}
public override void DrawTransport(Graphics g)
{
if (EntityWarAirplane is not EntityAirBomber airBomber)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(airBomber.AdditionalColor);
base.DrawTransport(g);
//Крылья
PointF point5 = new PointF(_startPosX + 50, _startPosY + 40);
PointF point6 = new PointF(_startPosX + 50, _startPosY + 0);
PointF point7 = new PointF(_startPosX + 55, _startPosY + 0);
PointF point8 = new PointF(_startPosX + 65, _startPosY + 40);
PointF[] upWing =
{
point5,
point6,
point7,
point8
};
g.FillPolygon(additionalBrush, upWing);
g.DrawPolygon(pen, upWing);
PointF point9 = new PointF(_startPosX + 50, _startPosY + 50);
PointF point10 = new PointF(_startPosX + 50, _startPosY + 90);
PointF point11 = new PointF(_startPosX + 55, _startPosY + 90);
PointF point12 = new PointF(_startPosX + 65, _startPosY + 50);
PointF[] downWing =
{
point9,
point10,
point11,
point12
};
g.FillPolygon(additionalBrush, downWing);
g.DrawPolygon(pen, downWing);
//Хвост
PointF point13 = new PointF(_startPosX + 30, _startPosY + 30);
PointF point14 = new PointF(_startPosX + 15, _startPosY + 0);
PointF point15 = new PointF(_startPosX + 15, _startPosY + 90);
PointF point16 = new PointF(_startPosX + 30, _startPosY + 60);
PointF[] tail =
{
point13,
point14,
point15,
point16
};
g.FillPolygon(additionalBrush, tail);
g.DrawPolygon(pen, tail);
if (airBomber.Bombs)
{
//бомбы
PointF point17 = new PointF(_startPosX + 40, _startPosY + 40);
PointF point18 = new PointF(_startPosX + 35, _startPosY + 35);
PointF point19 = new PointF(_startPosX + 40, _startPosY + 30);
PointF point20 = new PointF(_startPosX + 50, _startPosY + 40);
PointF[] bomb1 =
{
point17,
point18,
point19,
point20
};
Brush brBomb = new SolidBrush(Color.Gray);
g.FillPolygon(brBomb, bomb1);
g.DrawPolygon(pen, bomb1);
PointF point21 = new PointF(_startPosX + 40, _startPosY + 50);
PointF point22 = new PointF(_startPosX + 35, _startPosY + 55);
PointF point23 = new PointF(_startPosX + 40, _startPosY + 60);
PointF point24 = new PointF(_startPosX + 50, _startPosY + 50);
PointF[] bomb2 =
{
point21,
point22,
point23,
point24
};
g.FillPolygon(brBomb, bomb2);
g.DrawPolygon(pen, bomb2);
}
if (airBomber.FuelTank)
{
//топливные баки
Rectangle fuelTank = new Rectangle((int)_startPosX + 50, (int)_startPosY + 43, 20, 5);
g.FillRectangle(additionalBrush, fuelTank);
g.DrawRectangle(pen, fuelTank);
}
}
public void setAddColor(Color color)
{
if (EntityWarAirplane is EntityAirBomber airBomber)
{
airBomber.setAddColor(color);
}
}
}
}

View File

@ -0,0 +1,37 @@
using AirBomber.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AirBomber.DrawingObjects;
namespace AirBomber.MovementStrategy
{
internal class DrawingObjectWarAirplane : IMoveableObject
{
private readonly DrawingWarAirplane? _drawingWarAirplane = null;
public DrawingObjectWarAirplane(DrawingWarAirplane drawingWarAirplane)
{
_drawingWarAirplane = drawingWarAirplane;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_drawingWarAirplane == null || _drawingWarAirplane.EntityWarAirplane ==
null)
{
return null;
}
return new ObjectParameters(_drawingWarAirplane.GetPosX,
_drawingWarAirplane.GetPosY, _drawingWarAirplane.GetWidth, _drawingWarAirplane.GetHeight);
}
}
public int GetStep => (int)(_drawingWarAirplane?.EntityWarAirplane?.Step ?? 0);
public bool CheckCanMove(DirectionType direction) =>
_drawingWarAirplane?.CanMove(direction) ?? false;
public void MoveObject(DirectionType direction) =>
_drawingWarAirplane?.MoveTransport(direction);
}
}

View File

@ -0,0 +1,241 @@
using AirBomber.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AirBomber.Entities;
using AirBomber.MovementStrategy;
namespace AirBomber.DrawingObjects
{
public class DrawingWarAirplane
{
public EntityWarAirplane? EntityWarAirplane { get; protected set; }
private int _pictureWidth;
private int _pictureHeight;
protected int _startPosX;
protected int _startPosY;
protected readonly int _WarAirplaneWidth = 100;
protected readonly int _WarAirplaneHeight = 90;
public int GetPosX => _startPosX;
public int GetPosY => _startPosY;
public int GetWidth => _WarAirplaneWidth;
public int GetHeight => _WarAirplaneHeight;
public IMoveableObject GetMoveableObject => new DrawingObjectWarAirplane(this);
public DrawingWarAirplane(int speed, double weight, Color bodyColor,
int width, int height)
{
if (width < _WarAirplaneWidth || height < _WarAirplaneHeight)
{
return;
}
_pictureWidth = width;
_pictureHeight = height;
EntityWarAirplane = new EntityWarAirplane(speed, weight, bodyColor);
}
protected DrawingWarAirplane(int speed, double weight, Color bodyColor,
int width, int height, int WarAirplaneWidth, int WarAirplaneHeight)
{
if (width <= _WarAirplaneWidth || height <= _WarAirplaneHeight)
{
return;
}
_pictureWidth = width;
_pictureHeight = height;
_WarAirplaneWidth = WarAirplaneWidth;
_WarAirplaneHeight = WarAirplaneHeight;
EntityWarAirplane = new EntityWarAirplane(speed, weight, bodyColor);
}
public void SetPosition(int x, int y)
{
if (x < 0 || x >= _pictureWidth || y < 0 || y >= _pictureHeight)
{
_startPosX = 0;
_startPosY = 0;
}
_startPosX = x;
_startPosY = y;
}
public bool CanMove(DirectionType direction)
{
if (EntityWarAirplane == null)
{
return false;
}
return direction switch
{
//влево
DirectionType.Left => _startPosX - EntityWarAirplane.Step > 0,
//вверх
DirectionType.Up => _startPosY - EntityWarAirplane.Step > 0,
// вправо
DirectionType.Right => _startPosX + EntityWarAirplane.Step + _WarAirplaneWidth < _pictureWidth,
//вниз
DirectionType.Down => _startPosY + EntityWarAirplane.Step + _WarAirplaneHeight < _pictureHeight,
_ => false,
};
}
public void MoveTransport(DirectionType direction)
{
if (!CanMove(direction) || EntityWarAirplane == null)
{
return;
}
switch (direction)
{
//влево
case DirectionType.Left:
_startPosX -= (int)EntityWarAirplane.Step;
break;
//вверх
case DirectionType.Up:
_startPosY -= (int)EntityWarAirplane.Step;
break;
// вправо
case DirectionType.Right:
_startPosX += (int)EntityWarAirplane.Step;
break;
//вниз
case DirectionType.Down:
_startPosY += (int)EntityWarAirplane.Step;
break;
}
}
public virtual void DrawTransport(Graphics g)
{
if (EntityWarAirplane == null)
{
return;
}
Pen pen = new(Color.Black);
//нос бомбардировщика
PointF point1 = new PointF(_startPosX + 100, _startPosY + 45);
PointF point2 = new PointF(_startPosX + 80, _startPosY + 40);
PointF point3 = new PointF(_startPosX + 80, _startPosY + 50);
PointF point4 = new PointF(_startPosX + 100, _startPosY + 45);
PointF[] curvePoints =
{
point1,
point2,
point3,
point4
};
Brush br = new SolidBrush(Color.Gray);
g.FillPolygon(br, curvePoints);
g.DrawPolygon(pen, curvePoints);
//Крылья
PointF point5 = new PointF(_startPosX + 50, _startPosY + 40);
PointF point6 = new PointF(_startPosX + 50, _startPosY + 0);
PointF point7 = new PointF(_startPosX + 55, _startPosY + 0);
PointF point8 = new PointF(_startPosX + 65, _startPosY + 40);
PointF[] upWing =
{
point5,
point6,
point7,
point8
};
SolidBrush wingBrush = new SolidBrush(EntityWarAirplane.BodyColor);
g.FillPolygon(wingBrush, upWing);
g.DrawPolygon(pen, upWing);
PointF point9 = new PointF(_startPosX + 50, _startPosY + 50);
PointF point10 = new PointF(_startPosX + 50, _startPosY + 90);
PointF point11 = new PointF(_startPosX + 55, _startPosY + 90);
PointF point12 = new PointF(_startPosX + 65, _startPosY + 50);
PointF[] downWing =
{
point9,
point10,
point11,
point12
};
g.FillPolygon(wingBrush, downWing);
g.DrawPolygon(pen, downWing);
//Хвост
PointF point13 = new PointF(_startPosX + 30, _startPosY + 30);
PointF point14 = new PointF(_startPosX + 15, _startPosY + 0);
PointF point15 = new PointF(_startPosX + 15, _startPosY + 90);
PointF point16 = new PointF(_startPosX + 30, _startPosY + 60);
PointF[] tail =
{
point13,
point14,
point15,
point16
};
g.FillPolygon(wingBrush, tail);
g.DrawPolygon(pen, tail);
//основная часть бомбардировщика
SolidBrush bodyBrush = new SolidBrush(EntityWarAirplane.BodyColor);
Rectangle bodyAirBomber = new Rectangle((int)_startPosX + 30, (int)_startPosY + 40, 50, 10);
g.FillRectangle(bodyBrush, bodyAirBomber);
g.DrawRectangle(pen, bodyAirBomber);
//бомбы
PointF point17 = new PointF(_startPosX + 40, _startPosY + 40);
PointF point18 = new PointF(_startPosX + 35, _startPosY + 35);
PointF point19 = new PointF(_startPosX + 40, _startPosY + 30);
PointF point20 = new PointF(_startPosX + 50, _startPosY + 40);
PointF[] bomb1 =
{
point17,
point18,
point19,
point20
};
Brush brBomb = new SolidBrush(Color.Gray);
g.FillPolygon(brBomb, bomb1);
g.DrawPolygon(pen, bomb1);
PointF point21 = new PointF(_startPosX + 40, _startPosY + 50);
PointF point22 = new PointF(_startPosX + 35, _startPosY + 55);
PointF point23 = new PointF(_startPosX + 40, _startPosY + 60);
PointF point24 = new PointF(_startPosX + 50, _startPosY + 50);
PointF[] bomb2 =
{
point21,
point22,
point23,
point24
};
g.FillPolygon(brBomb, bomb2);
g.DrawPolygon(pen, bomb2);
}
public void setColor(Color color)
{
EntityWarAirplane.setColor(color);
}
}
}

View File

@ -0,0 +1,23 @@
using AirBomber.Entities;
using System;
namespace AirBomber.Entities
{
public class EntityAirBomber : EntityWarAirplane
{
public Color AdditionalColor { get; private set; }
public bool FuelTank { get; private set; }
public bool Bombs { get; private set; }
public EntityAirBomber(int speed, double weight, Color bodyColor, Color additionalColor, bool fuelTank,
bool bombs) : base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
FuelTank = fuelTank;
Bombs = bombs;
}
public void setAddColor(Color color)
{
AdditionalColor = color;
}
}
}

View File

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

View File

@ -0,0 +1,46 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AirBomber.Entities;
namespace AirBomber.DrawingObjects
{
public static class ExtentionDrawingWarAirplane
{
public static DrawingWarAirplane? CreateDrawingWarAirplane(this string info, char separatorForObject,
int width, int height)
{
string[] strs = info.Split(separatorForObject);
if(strs.Length == 3)
{
return new DrawingWarAirplane(Convert.ToInt32(strs[0]), Convert.ToInt32(strs[1]),
Color.FromName(strs[2]), width, height);
}
if(strs.Length == 6)
{
return new DrawingAirBomber(Convert.ToInt32(strs[0]), Convert.ToInt32(strs[1]),
Color.FromName(strs[2]), Color.FromName(strs[3]), Convert.ToBoolean(strs[4]),
Convert.ToBoolean(strs[5]), width, height);
}
return null;
}
public static string GetDataForSave(this DrawingWarAirplane drawingWarAirplane, char separatorForObject)
{
var warAirplane = drawingWarAirplane.EntityWarAirplane;
if(warAirplane == null)
{
return string.Empty;
}
var str = $"{warAirplane.Speed}{separatorForObject}{warAirplane.Weight}" +
$"{separatorForObject}{warAirplane.BodyColor.Name}";
if(warAirplane is not EntityAirBomber airBomber)
{
return str;
}
return $"{str}{separatorForObject}{airBomber.AdditionalColor.Name}{separatorForObject}" +
$"{airBomber.FuelTank}{separatorForObject}{airBomber.Bombs}";
}
}
}

View File

@ -1,39 +0,0 @@
namespace AirBomber
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Text = "Form1";
}
#endregion
}
}

View File

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

View File

@ -0,0 +1,188 @@
namespace AirBomber
{
partial class FormAirBomber
{
/// <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()
{
pictureBoxAirBomber = new PictureBox();
buttonCreateWarAirplane = new Button();
buttonUp = new Button();
buttonDown = new Button();
buttonLeft = new Button();
buttonRight = new Button();
buttonCreateAirBomber = new Button();
buttonStep = new Button();
comboBoxStrategy = new ComboBox();
ButtonSelectWarAirplane = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxAirBomber).BeginInit();
SuspendLayout();
//
// pictureBoxAirBomber
//
pictureBoxAirBomber.Dock = DockStyle.Fill;
pictureBoxAirBomber.Location = new Point(0, 0);
pictureBoxAirBomber.Name = "pictureBoxAirBomber";
pictureBoxAirBomber.Size = new Size(884, 461);
pictureBoxAirBomber.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBoxAirBomber.TabIndex = 0;
pictureBoxAirBomber.TabStop = false;
//
// buttonCreateWarAirplane
//
buttonCreateWarAirplane.Location = new Point(12, 394);
buttonCreateWarAirplane.Name = "buttonCreateWarAirplane";
buttonCreateWarAirplane.Size = new Size(156, 41);
buttonCreateWarAirplane.TabIndex = 1;
buttonCreateWarAirplane.Text = "Создать Военный самолёт";
buttonCreateWarAirplane.UseVisualStyleBackColor = true;
buttonCreateWarAirplane.Click += ButtonCreateWarAirplane_Click;
//
// buttonUp
//
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = Properties.Resources.arrowUp;
buttonUp.BackgroundImageLayout = ImageLayout.Zoom;
buttonUp.Location = new Point(786, 357);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(30, 30);
buttonUp.TabIndex = 2;
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += ButtonMove_Click;
//
// buttonDown
//
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = Properties.Resources.arrowDown;
buttonDown.BackgroundImageLayout = ImageLayout.Zoom;
buttonDown.Location = new Point(786, 393);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(30, 30);
buttonDown.TabIndex = 3;
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += ButtonMove_Click;
//
// buttonLeft
//
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = Properties.Resources.arrowLeft;
buttonLeft.BackgroundImageLayout = ImageLayout.Zoom;
buttonLeft.Location = new Point(750, 393);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(30, 30);
buttonLeft.TabIndex = 4;
buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.Click += ButtonMove_Click;
//
// buttonRight
//
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = Properties.Resources.arrowRight;
buttonRight.BackgroundImageLayout = ImageLayout.Zoom;
buttonRight.Location = new Point(822, 393);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(30, 30);
buttonRight.TabIndex = 5;
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click;
//
// buttonCreateAirBomber
//
buttonCreateAirBomber.Location = new Point(193, 394);
buttonCreateAirBomber.Name = "buttonCreateAirBomber";
buttonCreateAirBomber.Size = new Size(156, 41);
buttonCreateAirBomber.TabIndex = 6;
buttonCreateAirBomber.Text = "Создать Бомбардировщик";
buttonCreateAirBomber.UseVisualStyleBackColor = true;
buttonCreateAirBomber.Click += ButtonCreateAirBomber_Click;
//
// buttonStep
//
buttonStep.Location = new Point(774, 74);
buttonStep.Name = "buttonStep";
buttonStep.Size = new Size(78, 29);
buttonStep.TabIndex = 7;
buttonStep.Text = "Шаг";
buttonStep.UseVisualStyleBackColor = true;
buttonStep.Click += buttonStep_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "MoveToCenter", "MoveToBorder" });
comboBoxStrategy.Location = new Point(696, 30);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(156, 23);
comboBoxStrategy.TabIndex = 8;
//
// ButtonSelectWarAirplane
//
ButtonSelectWarAirplane.Location = new Point(379, 394);
ButtonSelectWarAirplane.Name = "ButtonSelectWarAirplane";
ButtonSelectWarAirplane.Size = new Size(156, 41);
ButtonSelectWarAirplane.TabIndex = 9;
ButtonSelectWarAirplane.Text = "Выбрать самолёт";
ButtonSelectWarAirplane.UseVisualStyleBackColor = true;
ButtonSelectWarAirplane.Click += ButtonSelectWarAirplane_Click;
//
// FormAirBomber
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(884, 461);
Controls.Add(ButtonSelectWarAirplane);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonStep);
Controls.Add(buttonCreateAirBomber);
Controls.Add(buttonRight);
Controls.Add(buttonLeft);
Controls.Add(buttonDown);
Controls.Add(buttonUp);
Controls.Add(buttonCreateWarAirplane);
Controls.Add(pictureBoxAirBomber);
Name = "FormAirBomber";
StartPosition = FormStartPosition.CenterScreen;
Text = "FormAirBomber";
((System.ComponentModel.ISupportInitialize)pictureBoxAirBomber).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private PictureBox pictureBoxAirBomber;
private Button buttonCreateWarAirplane;
private Button buttonUp;
private Button buttonDown;
private Button buttonLeft;
private Button buttonRight;
private Button buttonCreateAirBomber;
private Button buttonStep;
private ComboBox comboBoxStrategy;
private Button ButtonSelectWarAirplane;
}
}

View File

@ -0,0 +1,137 @@
using AirBomber.DrawingObjects;
using AirBomber.MovementStrategy;
using System.Drawing;
using System;
using System.Windows.Forms;
namespace AirBomber
{
public partial class FormAirBomber : Form
{
private DrawingWarAirplane? _drawingWarAirplane;
private AbstractStrategy? _abstractStrategy;
public DrawingWarAirplane? SelectedWarAirplane { get; private set; }
public FormAirBomber()
{
InitializeComponent();
_abstractStrategy = null;
SelectedWarAirplane = null;
}
private void Draw()
{
if(_drawingWarAirplane == null)
{
return;
}
Bitmap bmp = new(pictureBoxAirBomber.Width, pictureBoxAirBomber.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawingWarAirplane.DrawTransport(gr);
pictureBoxAirBomber.Image = bmp;
}
private void ButtonCreateAirBomber_Click(object sender, EventArgs e)
{
Random rnd = new();
Color color = Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256));
Color additionalColor = 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;
}
if (dialog.ShowDialog() == DialogResult.OK)
{
additionalColor = dialog.Color;
}
_drawingWarAirplane = new DrawingAirBomber(rnd.Next(100, 300), rnd.Next(1000, 2000),
color, additionalColor, Convert.ToBoolean(rnd.Next(0, 2)), Convert.ToBoolean(rnd.Next(0, 2)),
pictureBoxAirBomber.Width, pictureBoxAirBomber.Height);
_drawingWarAirplane.SetPosition(rnd.Next(10, 100), rnd.Next(10, 100));
Draw();
}
private void ButtonCreateWarAirplane_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;
}
_drawingWarAirplane = new DrawingWarAirplane(rnd.Next(100, 300), rnd.Next(1000, 2000),
color, pictureBoxAirBomber.Width, pictureBoxAirBomber.Height);
_drawingWarAirplane.SetPosition(rnd.Next(10, 100), rnd.Next(10, 100));
Draw();
}
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawingWarAirplane == null)
{
return;
}
//äâèæåíèå
string name = ((Button)sender)?.Name ?? string.Empty;
switch (name)
{
case "buttonUp":
_drawingWarAirplane?.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
_drawingWarAirplane?.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
_drawingWarAirplane?.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
_drawingWarAirplane?.MoveTransport(DirectionType.Right);
break;
}
Draw();
}
private void buttonStep_Click(object sender, EventArgs e)
{
if (_drawingWarAirplane == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_abstractStrategy = comboBoxStrategy.SelectedIndex
switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(_drawingWarAirplane.GetMoveableObject, pictureBoxAirBomber.Width,
pictureBoxAirBomber.Height);
}
if (_abstractStrategy == null)
{
return;
}
comboBoxStrategy.Enabled = false;
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_abstractStrategy = null;
}
}
private void ButtonSelectWarAirplane_Click(object sender, EventArgs e)
{
SelectedWarAirplane = _drawingWarAirplane;
DialogResult = DialogResult.OK;
}
}
}

View File

@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
@ -26,36 +26,36 @@
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->

View File

@ -0,0 +1,253 @@
namespace AirBomber
{
partial class FormWarAirplaneCollection
{
/// <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()
{
panelCollection = new Panel();
panelObject = new Panel();
textBoxStorageName = new TextBox();
buttonAddObject = new Button();
buttonDelObject = new Button();
listBoxStorages = new ListBox();
Tools = new Label();
buttonRefreshCollection = new Button();
buttonRemove = new Button();
buttonAdd = new Button();
maskedTextBoxNumber = new MaskedTextBox();
pictureBoxCollection = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
SaveToolStripMenuItem = new ToolStripMenuItem();
LoadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
panelCollection.SuspendLayout();
panelObject.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// panelCollection
//
panelCollection.Controls.Add(panelObject);
panelCollection.Controls.Add(Tools);
panelCollection.Controls.Add(buttonRefreshCollection);
panelCollection.Controls.Add(buttonRemove);
panelCollection.Controls.Add(buttonAdd);
panelCollection.Controls.Add(maskedTextBoxNumber);
panelCollection.Dock = DockStyle.Right;
panelCollection.Location = new Point(617, 24);
panelCollection.Name = "panelCollection";
panelCollection.Size = new Size(183, 456);
panelCollection.TabIndex = 0;
//
// panelObject
//
panelObject.Controls.Add(textBoxStorageName);
panelObject.Controls.Add(buttonAddObject);
panelObject.Controls.Add(buttonDelObject);
panelObject.Controls.Add(listBoxStorages);
panelObject.Location = new Point(6, 27);
panelObject.Name = "panelObject";
panelObject.Size = new Size(171, 214);
panelObject.TabIndex = 4;
//
// textBoxStorageName
//
textBoxStorageName.Location = new Point(7, 19);
textBoxStorageName.Name = "textBoxStorageName";
textBoxStorageName.Size = new Size(158, 23);
textBoxStorageName.TabIndex = 2;
//
// buttonAddObject
//
buttonAddObject.Location = new Point(7, 48);
buttonAddObject.Name = "buttonAddObject";
buttonAddObject.Size = new Size(158, 31);
buttonAddObject.TabIndex = 2;
buttonAddObject.Text = "Добавить объект";
buttonAddObject.UseVisualStyleBackColor = true;
buttonAddObject.Click += ButtonAddObject_Click;
//
// buttonDelObject
//
buttonDelObject.Location = new Point(7, 167);
buttonDelObject.Name = "buttonDelObject";
buttonDelObject.Size = new Size(158, 31);
buttonDelObject.TabIndex = 2;
buttonDelObject.Text = "Удалить объект";
buttonDelObject.UseVisualStyleBackColor = true;
buttonDelObject.Click += ButtonDelObject__Click;
//
// listBoxStorages
//
listBoxStorages.FormattingEnabled = true;
listBoxStorages.ItemHeight = 15;
listBoxStorages.Location = new Point(7, 85);
listBoxStorages.Name = "listBoxStorages";
listBoxStorages.Size = new Size(158, 64);
listBoxStorages.TabIndex = 2;
listBoxStorages.SelectedIndexChanged += ListBoxObjects_SelectedIndexChanged;
//
// Tools
//
Tools.AutoSize = true;
Tools.Location = new Point(53, 9);
Tools.Name = "Tools";
Tools.Size = new Size(83, 15);
Tools.TabIndex = 3;
Tools.Text = "Инструменты";
//
// buttonRefreshCollection
//
buttonRefreshCollection.Location = new Point(3, 395);
buttonRefreshCollection.Name = "buttonRefreshCollection";
buttonRefreshCollection.Size = new Size(174, 43);
buttonRefreshCollection.TabIndex = 2;
buttonRefreshCollection.Text = "Обновить коллекцию";
buttonRefreshCollection.UseVisualStyleBackColor = true;
buttonRefreshCollection.Click += ButtonRefreshCollection_Click;
//
// buttonRemove
//
buttonRemove.Location = new Point(3, 336);
buttonRemove.Name = "buttonRemove";
buttonRemove.Size = new Size(174, 31);
buttonRemove.TabIndex = 2;
buttonRemove.Text = "Удалить военный самолёт";
buttonRemove.UseVisualStyleBackColor = true;
buttonRemove.Click += ButtonRemoveWarAirplane_Click;
//
// buttonAdd
//
buttonAdd.Location = new Point(3, 255);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(174, 31);
buttonAdd.TabIndex = 2;
buttonAdd.Text = "Добавить военный самолёт";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAddWarAirplane_Click;
//
// maskedTextBoxNumber
//
maskedTextBoxNumber.Location = new Point(3, 307);
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(174, 23);
maskedTextBoxNumber.TabIndex = 0;
//
// pictureBoxCollection
//
pictureBoxCollection.Dock = DockStyle.Left;
pictureBoxCollection.Location = new Point(0, 24);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(617, 456);
pictureBoxCollection.TabIndex = 1;
pictureBoxCollection.TabStop = false;
//
// menuStrip
//
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(800, 24);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { SaveToolStripMenuItem, LoadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(48, 20);
файлToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
SaveToolStripMenuItem.Size = new Size(133, 22);
SaveToolStripMenuItem.Text = "Сохранить";
SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// LoadToolStripMenuItem
//
LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
LoadToolStripMenuItem.Size = new Size(133, 22);
LoadToolStripMenuItem.Text = "Загрузить";
LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// openFileDialog
//
openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// FormWarAirplaneCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 480);
Controls.Add(pictureBoxCollection);
Controls.Add(panelCollection);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormWarAirplaneCollection";
Text = "Набор военных самолётов";
panelCollection.ResumeLayout(false);
panelCollection.PerformLayout();
panelObject.ResumeLayout(false);
panelObject.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
private Panel panelCollection;
private PictureBox pictureBoxCollection;
private Label Tools;
private Button buttonRefreshCollection;
private Button buttonRemove;
private Button buttonAdd;
private MaskedTextBox maskedTextBoxNumber;
private ListBox listBoxStorages;
private Button buttonAddObject;
private Button buttonDelObject;
private Panel panelObject;
private TextBox textBoxStorageName;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
}
}

View File

@ -0,0 +1,238 @@
using AirBomber.Generics;
using AirBomber.DrawingObjects;
using AirBomber.MovementStrategy;
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 Microsoft.Extensions.Logging;
using AirBomber.Exceptions;
using System.Xml.Linq;
using Serilog;
namespace AirBomber
{
public partial class FormWarAirplaneCollection : Form
{
private readonly WarAirplaneGenericStorage _storage;
public FormWarAirplaneCollection()
{
InitializeComponent();
_storage = new WarAirplaneGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
}
private void ReloadObjects()
{
int index = listBoxStorages.SelectedIndex;
listBoxStorages.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++)
{
listBoxStorages.Items.Add(_storage.Keys[i]);
}
if (listBoxStorages.Items.Count > 0 && (index == -1 || index
>= listBoxStorages.Items.Count))
{
listBoxStorages.SelectedIndex = 0;
}
else if (listBoxStorages.Items.Count > 0 && index > -1 &&
index < listBoxStorages.Items.Count)
{
listBoxStorages.SelectedIndex = index;
}
}
private void ButtonAddObject_Click(object sender, EventArgs e) //работает
{
if (string.IsNullOrEmpty(textBoxStorageName.Text.ToString() ?? string.Empty))
{
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
Log.Information($"Добавлен набор: {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
}
private void ButtonDelObject__Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
if (MessageBox.Show($"Удалить набор {listBoxStorages.SelectedItem.ToString() ?? string.Empty}?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
if (listBoxStorages.SelectedIndex == null)
{
return;
}
Log.Information($"Удален набор: {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
_storage.DelSet(listBoxStorages.SelectedItem.ToString()
?? string.Empty);
ReloadObjects();
}
}
private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBoxCollection.Image =
_storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowWarAirplane();
}
private void ButtonAddWarAirplane_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
FormWarAirplaneConfig form = new FormWarAirplaneConfig();
form.Show();
Action<DrawingWarAirplane>? warAirplaneDelegate = new((m) =>
{
try
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
//int pos = Convert.ToInt32(maskedTextBoxNumber.Text); // TO DO
var q = obj + m;
if(q != -1)
{
MessageBox.Show("Объект добавлен");
Log.Information($"Добавлен объект в набор {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
pictureBoxCollection.Image = obj.ShowWarAirplane();
}
else
{
MessageBox.Show("Не удалось добавить объект");
Log.Information("Не удалось добавить объект");
}
}
catch (StorageOverflowException ex)
{
Log.Warning($"Коллекция {listBoxStorages.SelectedItem.ToString() ?? string.Empty} переполнена");
MessageBox.Show(ex.Message);
}
});
form.AddEvent(warAirplaneDelegate);
}
private void ButtonRemoveWarAirplane_Click(object sender, EventArgs e)
{
try
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
Log.Information("Не удалось удалить объект. Объект равен null");
MessageBox.Show("Не удалось удалить объект");
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
if (maskedTextBoxNumber.Text == null)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
var q = obj - pos;
MessageBox.Show("Объект удален");
Log.Information($"Удален объект номер {pos} из набора {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
pictureBoxCollection.Image = obj.ShowWarAirplane();
}
catch (WarAirplaneNotFoundException ex)
{
Log.Warning($"Не получилось удалить объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
MessageBox.Show(ex.Message);
}
catch (FormatException ex)
{
Log.Warning($"Было введено не число");
MessageBox.Show("Введите число");
}
}
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
pictureBoxCollection.Image = obj.ShowWarAirplane();
}
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
Log.Information($"Данные загружены в файл {saveFileDialog.FileName}");
}
catch(Exception ex)
{
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
Log.Warning($"Не удалось сохранить информацию в файл: {ex.Message}");
}
}
}
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
foreach (var collection in _storage.Keys)
{
listBoxStorages.Items.Add(collection);
}
Log.Information($"Данные загружены из файла {openFileDialog.FileName}");
}
catch(Exception ex)
{
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
Log.Warning($"Не удалось загрузить информацию из файла: {ex.Message}");
}
}
}
}
}

View File

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

View File

@ -0,0 +1,370 @@
namespace AirBomber
{
partial class FormWarAirplaneConfig
{
/// <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()
{
groupBoxParameters = new GroupBox();
labelModifiedObject = new Label();
labelSimpleObject = new Label();
checkBoxBombs = new CheckBox();
checkBoxFuelTank = new CheckBox();
numericUpDownWeight = new NumericUpDown();
numericUpDownSpeed = new NumericUpDown();
labelWeight = new Label();
labelSpeed = new Label();
groupBoxColors = new GroupBox();
panelPurple = new Panel();
panelBlack = new Panel();
panelGray = new Panel();
panelWhite = new Panel();
panelYellow = new Panel();
panelBlue = new Panel();
panelGreen = new Panel();
panelRed = new Panel();
groupBoxObject = new GroupBox();
panelObject = new Panel();
pictureBoxObject = new PictureBox();
labelAddColor = new Label();
labelColor = new Label();
buttonAdd = new Button();
buttonCancel = new Button();
groupBoxParameters.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
groupBoxColors.SuspendLayout();
groupBoxObject.SuspendLayout();
panelObject.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
SuspendLayout();
//
// groupBoxParameters
//
groupBoxParameters.Controls.Add(labelModifiedObject);
groupBoxParameters.Controls.Add(labelSimpleObject);
groupBoxParameters.Controls.Add(checkBoxBombs);
groupBoxParameters.Controls.Add(checkBoxFuelTank);
groupBoxParameters.Controls.Add(numericUpDownWeight);
groupBoxParameters.Controls.Add(numericUpDownSpeed);
groupBoxParameters.Controls.Add(labelWeight);
groupBoxParameters.Controls.Add(labelSpeed);
groupBoxParameters.Controls.Add(groupBoxColors);
groupBoxParameters.Location = new Point(11, 12);
groupBoxParameters.Name = "groupBoxParameters";
groupBoxParameters.Size = new Size(515, 300);
groupBoxParameters.TabIndex = 0;
groupBoxParameters.TabStop = false;
groupBoxParameters.Text = "Параметры";
//
// labelModifiedObject
//
labelModifiedObject.BorderStyle = BorderStyle.FixedSingle;
labelModifiedObject.Location = new Point(385, 192);
labelModifiedObject.Name = "labelModifiedObject";
labelModifiedObject.Size = new Size(90, 50);
labelModifiedObject.TabIndex = 8;
labelModifiedObject.Text = "Продвинутый";
labelModifiedObject.TextAlign = ContentAlignment.MiddleCenter;
labelModifiedObject.MouseDown += LabelObject_MouseDown;
//
// labelSimpleObject
//
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Location = new Point(251, 192);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(90, 50);
labelSimpleObject.TabIndex = 7;
labelSimpleObject.Text = "Простой";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
labelSimpleObject.MouseDown += LabelObject_MouseDown;
//
// checkBoxBombs
//
checkBoxBombs.AutoSize = true;
checkBoxBombs.Location = new Point(23, 155);
checkBoxBombs.Name = "checkBoxBombs";
checkBoxBombs.Size = new Size(65, 19);
checkBoxBombs.TabIndex = 6;
checkBoxBombs.Text = "Бомбы";
checkBoxBombs.UseVisualStyleBackColor = true;
//
// checkBoxFuelTank
//
checkBoxFuelTank.AutoSize = true;
checkBoxFuelTank.Location = new Point(23, 120);
checkBoxFuelTank.Name = "checkBoxFuelTank";
checkBoxFuelTank.Size = new Size(210, 19);
checkBoxFuelTank.TabIndex = 5;
checkBoxFuelTank.Text = "Дополнительный топливный бак";
checkBoxFuelTank.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(105, 70);
numericUpDownWeight.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownWeight.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownWeight.Name = "numericUpDownWeight";
numericUpDownWeight.Size = new Size(120, 23);
numericUpDownWeight.TabIndex = 4;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(105, 37);
numericUpDownSpeed.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownSpeed.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownSpeed.Name = "numericUpDownSpeed";
numericUpDownSpeed.Size = new Size(120, 23);
numericUpDownSpeed.TabIndex = 3;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelWeight
//
labelWeight.AutoSize = true;
labelWeight.Location = new Point(25, 72);
labelWeight.Name = "labelWeight";
labelWeight.Size = new Size(29, 15);
labelWeight.TabIndex = 2;
labelWeight.Text = "Вес:";
//
// labelSpeed
//
labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(25, 39);
labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(62, 15);
labelSpeed.TabIndex = 1;
labelSpeed.Text = "Скорость:";
//
// groupBoxColors
//
groupBoxColors.Controls.Add(panelPurple);
groupBoxColors.Controls.Add(panelBlack);
groupBoxColors.Controls.Add(panelGray);
groupBoxColors.Controls.Add(panelWhite);
groupBoxColors.Controls.Add(panelYellow);
groupBoxColors.Controls.Add(panelBlue);
groupBoxColors.Controls.Add(panelGreen);
groupBoxColors.Controls.Add(panelRed);
groupBoxColors.Location = new Point(240, 24);
groupBoxColors.Name = "groupBoxColors";
groupBoxColors.Size = new Size(248, 150);
groupBoxColors.TabIndex = 0;
groupBoxColors.TabStop = false;
groupBoxColors.Text = "Цвета";
//
// panelPurple
//
panelPurple.BackColor = Color.Purple;
panelPurple.Location = new Point(190, 85);
panelPurple.Name = "panelPurple";
panelPurple.Size = new Size(45, 45);
panelPurple.TabIndex = 7;
//
// panelBlack
//
panelBlack.BackColor = Color.Black;
panelBlack.Location = new Point(132, 85);
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(45, 45);
panelBlack.TabIndex = 6;
//
// panelGray
//
panelGray.BackColor = Color.FromArgb(64, 64, 64);
panelGray.Location = new Point(72, 85);
panelGray.Name = "panelGray";
panelGray.Size = new Size(45, 45);
panelGray.TabIndex = 5;
//
// panelWhite
//
panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(11, 85);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(45, 45);
panelWhite.TabIndex = 4;
//
// panelYellow
//
panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(190, 24);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(45, 45);
panelYellow.TabIndex = 3;
//
// panelBlue
//
panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(132, 24);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(45, 45);
panelBlue.TabIndex = 2;
//
// panelGreen
//
panelGreen.BackColor = Color.Green;
panelGreen.Location = new Point(72, 24);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(45, 45);
panelGreen.TabIndex = 1;
//
// panelRed
//
panelRed.BackColor = Color.Red;
panelRed.Location = new Point(11, 24);
panelRed.Name = "panelRed";
panelRed.Size = new Size(45, 45);
panelRed.TabIndex = 0;
//
// groupBoxObject
//
groupBoxObject.Controls.Add(panelObject);
groupBoxObject.Location = new Point(532, 11);
groupBoxObject.Name = "groupBoxObject";
groupBoxObject.Size = new Size(256, 268);
groupBoxObject.TabIndex = 1;
groupBoxObject.TabStop = false;
//
// panelObject
//
panelObject.AllowDrop = true;
panelObject.Controls.Add(pictureBoxObject);
panelObject.Controls.Add(labelAddColor);
panelObject.Controls.Add(labelColor);
panelObject.Location = new Point(6, 22);
panelObject.Name = "panelObject";
panelObject.Size = new Size(244, 240);
panelObject.TabIndex = 3;
panelObject.DragDrop += PanelObject_DragDrop;
panelObject.DragEnter += PanelObject_DragEnter;
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(8, 65);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(224, 172);
pictureBoxObject.TabIndex = 2;
pictureBoxObject.TabStop = false;
//
// labelAddColor
//
labelAddColor.AllowDrop = true;
labelAddColor.BorderStyle = BorderStyle.FixedSingle;
labelAddColor.Location = new Point(123, 16);
labelAddColor.Name = "labelAddColor";
labelAddColor.Size = new Size(109, 40);
labelAddColor.TabIndex = 1;
labelAddColor.Text = "Дополнительный цвет";
labelAddColor.TextAlign = ContentAlignment.MiddleCenter;
labelAddColor.DragDrop += LabelAddColor_DragDrop;
labelAddColor.DragEnter += LabelColor_DragEnter;
//
// labelColor
//
labelColor.AllowDrop = true;
labelColor.BorderStyle = BorderStyle.FixedSingle;
labelColor.Location = new Point(8, 16);
labelColor.Name = "labelColor";
labelColor.Size = new Size(109, 40);
labelColor.TabIndex = 0;
labelColor.Text = "Основной цвет";
labelColor.TextAlign = ContentAlignment.MiddleCenter;
labelColor.DragDrop += LabelColor_DragDrop;
labelColor.DragEnter += LabelColor_DragEnter;
//
// buttonAdd
//
buttonAdd.Location = new Point(538, 285);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(105, 29);
buttonAdd.TabIndex = 2;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += buttonAdd_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(687, 285);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(97, 27);
buttonCancel.TabIndex = 3;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += buttonCancel_Click;
//
// FormWarAirplaneConfig
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 336);
Controls.Add(buttonCancel);
Controls.Add(buttonAdd);
Controls.Add(groupBoxObject);
Controls.Add(groupBoxParameters);
Name = "FormWarAirplaneConfig";
Text = "FormWarAirplaneConfig";
groupBoxParameters.ResumeLayout(false);
groupBoxParameters.PerformLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).EndInit();
groupBoxColors.ResumeLayout(false);
groupBoxObject.ResumeLayout(false);
panelObject.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)pictureBoxObject).EndInit();
ResumeLayout(false);
}
#endregion
private GroupBox groupBoxParameters;
private Label labelSpeed;
private GroupBox groupBoxColors;
private GroupBox groupBoxObject;
private Label labelModifiedObject;
private Label labelSimpleObject;
private CheckBox checkBoxBombs;
private CheckBox checkBoxFuelTank;
private NumericUpDown numericUpDownWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelWeight;
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 Label labelAddColor;
private Label labelColor;
private Button buttonAdd;
private Button buttonCancel;
private Panel panelObject;
}
}

View File

@ -0,0 +1,149 @@
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 AirBomber.DrawingObjects;
namespace AirBomber
{
public partial class FormWarAirplaneConfig : Form
{
DrawingWarAirplane? _WarAirplane = null;
public event Action<DrawingWarAirplane>? EventAddWarAirplane;
public FormWarAirplaneConfig()
{
InitializeComponent();
panelBlack.MouseDown += PanelColor_MouseDown;
panelPurple.MouseDown += PanelColor_MouseDown;
panelYellow.MouseDown += PanelColor_MouseDown;
panelWhite.MouseDown += PanelColor_MouseDown;
panelGreen.MouseDown += PanelColor_MouseDown;
panelGray.MouseDown += PanelColor_MouseDown;
panelBlue.MouseDown += PanelColor_MouseDown;
panelRed.MouseDown += PanelColor_MouseDown;
buttonCancel.Click += (s, e) => Close();
}
private void DrawWarAirplane()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_WarAirplane?.SetPosition(5, 5);
_WarAirplane?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
private void PanelColor_MouseDown(object sender, MouseEventArgs e)
{
(sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor,
DragDropEffects.Move | DragDropEffects.Copy);
}
private void LabelColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)))
e.Effect = DragDropEffects.Copy;
else
{
e.Effect = DragDropEffects.None;
}
}
private void LabelColor_DragDrop(object sender, DragEventArgs e)
{
if (_WarAirplane is DrawingWarAirplane WarAirplane)
{
labelColor.BackColor = (Color)e.Data.GetData(typeof(Color));
_WarAirplane.setColor((Color)e.Data.GetData(typeof(Color)));
}
DrawWarAirplane();
}
private void LabelAddColor_DragDrop(object sender, DragEventArgs e)
{
if (_WarAirplane is DrawingAirBomber WarAirplane)
{
labelAddColor.BackColor = (Color)e.Data.GetData(typeof(Color));
((DrawingAirBomber)_WarAirplane).setAddColor((Color)e.Data.GetData(typeof(Color)));
}
DrawWarAirplane();
}
private void LabelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label)?.DoDragDrop((sender as Label)?.Name,
DragDropEffects.Move | DragDropEffects.Copy);
}
private void PanelObject_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(DataFormats.Text) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void PanelObject_DragDrop(object sender, DragEventArgs e)
{
switch (e.Data?.GetData(DataFormats.Text).ToString())
{
case "labelSimpleObject":
_WarAirplane = new DrawingWarAirplane((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, pictureBoxObject.Width,
pictureBoxObject.Height);
labelColor.BackColor = Color.White;
labelAddColor.BackColor = Color.Transparent;
break;
case "labelModifiedObject":
_WarAirplane = new DrawingAirBomber((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, Color.Black, checkBoxFuelTank.Checked,
checkBoxBombs.Checked, pictureBoxObject.Width,
pictureBoxObject.Height);
labelColor.BackColor = Color.White;
labelAddColor.BackColor = Color.Black;
break;
}
DrawWarAirplane();
}
public void AddEvent(Action<DrawingWarAirplane> ev)
{
if (EventAddWarAirplane == null)
{
EventAddWarAirplane = ev;
}
else
{
EventAddWarAirplane += ev;
}
}
private void buttonAdd_Click(object sender, EventArgs e)
{
EventAddWarAirplane?.Invoke(_WarAirplane);
Close();
}
private void buttonCancel_Click(object sender, EventArgs e)
{
Close();
}
}
}

View File

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

View File

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

View File

@ -0,0 +1,60 @@
using AirBomber.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirBomber.MovementStrategy
{
internal class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.RightBorder <= FieldWidth &&
objParams.RightBorder + GetStep() >= FieldWidth &&
objParams.DownBorder <= FieldHeight &&
objParams.DownBorder + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
var diffX = objParams.RightBorder - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = objParams.DownBorder - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}
}

View File

@ -0,0 +1,58 @@
using AirBomber.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirBomber.MovementStrategy
{
internal class MoveToCenter : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return (objParams.ObjectMiddleHorizontal <= FieldWidth / 2 &&
objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 &&
objParams.ObjectMiddleVertical <= FieldHeight / 2 &&
objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2);
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
var diffX = objParams.ObjectMiddleHorizontal - FieldWidth / 2;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = objParams.ObjectMiddleVertical - FieldHeight / 2;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}
}

View File

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

View File

@ -1,3 +1,12 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using Serilog;
using Serilog.Events;
using Serilog.Formatting.Json;
using Serilog.Configuration;
namespace AirBomber
{
internal static class Program
@ -6,12 +15,27 @@ namespace AirBomber
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
ApplicationConfiguration.Initialize(); string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: $"{pathNeed}appSetting.json", optional: false, reloadOnChange: true)
.Build();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormWarAirplaneCollection());
}
}
}
}

View File

@ -0,0 +1,103 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace AirBomber.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AirBomber.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap arrowDown {
get {
object obj = ResourceManager.GetObject("arrowDown", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap arrowLeft {
get {
object obj = ResourceManager.GetObject("arrowLeft", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap arrowRight {
get {
object obj = ResourceManager.GetObject("arrowRight", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap arrowUp {
get {
object obj = ResourceManager.GetObject("arrowUp", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

View File

@ -0,0 +1,81 @@
using AirBomber.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirBomber.Generics
{
internal class SetGeneric<T>
where T : class
{
private readonly List<T?> _places;
public int Count => _places.Count;
public int startPointer = 0;
public readonly int _maxCount;
public SetGeneric(int count)
{
_maxCount = count;
_places = new List<T?>(count);
}
public int Insert(T WarAirplane)
{
if (_places.Count == _maxCount) { throw new StorageOverflowException(_maxCount); }
Insert(WarAirplane, 0);
return 1;
}
public int Insert(T WarAirplane, int position)
{
if (_places.Count == _maxCount)
throw new StorageOverflowException(_maxCount);
if (!(position >= 0 && position <= Count)) return -1;
_places.Insert(position, WarAirplane);
return position;
}
public bool Remove(int position)
{
if (position < 0 || position >= Count)
throw new WarAirplaneNotFoundException(position);
_places.RemoveAt(position);
return true;
}
public T? this[int position]
{
get
{
if (!(position >= 0 && position < Count))
return null;
return _places[position];
}
set
{
if (!(position >= 0 && position < Count && _places.Count < _maxCount))
return;
_places.Insert(position, value);
return;
}
}
public IEnumerable<T?> GetWarAirplane(int? maxWarAirplane = null)
{
for (int i = 0; i < _places.Count; ++i)
{
yield return _places[i];
if (maxWarAirplane.HasValue && i == maxWarAirplane.Value)
{
yield break;
}
}
}
public T? Get(int position)
{
if (position < Count && position >= 0) { return _places[position]; }
return null;
}
}
}

View File

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

View File

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

View File

@ -0,0 +1,91 @@
using AirBomber.MovementStrategy;
using AirBomber.DrawingObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace AirBomber.Generics
{
internal class WarAirplaneGenericCollection<T, U>
where T : DrawingWarAirplane
where U : IMoveableObject
{
public IEnumerable<T?> GetWarAirplane => _collection.GetWarAirplane();
private readonly int _pictureWidth;
private readonly int _pictureHeight;
private readonly int _placeSizeWidth = 110;
private readonly int _placeSizeHeight = 110;
private readonly SetGeneric<T> _collection;
public IEnumerable<T?> GetWarAirplanes => _collection.GetWarAirplane();
public WarAirplaneGenericCollection(int picWidth, int picHeight)
{
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = new SetGeneric<T>(width * height);
}
public static int operator +(WarAirplaneGenericCollection<T, U> collect, T?
obj)
{
if (obj == null)
{
return -1;
}
collect._collection.Insert(obj);
return 1;
}
public static T? operator -(WarAirplaneGenericCollection<T, U> collect, int
pos)
{
T? obj = collect._collection[pos];
collect._collection.Remove(pos);
return obj;
}
public U? GetU(int pos)
{
return (U?)_collection.Get(pos)?.GetMoveableObject;
}
public Bitmap ShowWarAirplane()
{
Bitmap bmp = new(_pictureWidth, _pictureHeight);
Graphics gr = Graphics.FromImage(bmp);
DrawBackground(gr);
DrawObjects(gr);
return bmp;
}
private void DrawBackground(Graphics g)
{
Pen pen = new(Color.Black, 3);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight +
1; ++j)
{//линия рамзетки места
g.DrawLine(pen, i * _placeSizeWidth, j *
_placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth / 2, j *
_placeSizeHeight);
}
g.DrawLine(pen, i * _placeSizeWidth, 0, i *
_placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight);
}
}
private void DrawObjects(Graphics g)
{
int numPlacesInRow = _pictureWidth / _placeSizeWidth;
int i = 0;
foreach (var warAirplane in _collection.GetWarAirplane()) {
if (warAirplane != null)
{
warAirplane.SetPosition((i % numPlacesInRow) * _placeSizeWidth + _placeSizeWidth / 20, _placeSizeHeight * (i / numPlacesInRow) + _placeSizeHeight / 10);
warAirplane.DrawTransport(g);
}
i+=1;
}
}
}
}

View File

@ -0,0 +1,141 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AirBomber.DrawingObjects;
using AirBomber.MovementStrategy;
namespace AirBomber.Generics
{
internal class WarAirplaneGenericStorage
{
readonly Dictionary<string, WarAirplaneGenericCollection<DrawingWarAirplane,
DrawingObjectWarAirplane>> _warAirplaneStorages;
public List<string> Keys => _warAirplaneStorages.Keys.ToList();
private readonly int _pictureWidth;
private readonly int _pictureHeight;
private static readonly char _separatorForKeyValue = '|';
private readonly char _separatorRecords = ';';
private static readonly char _separatorForObject = ':';
public WarAirplaneGenericStorage(int pictureWidth, int pictureHeight)
{
_warAirplaneStorages = new Dictionary<string, WarAirplaneGenericCollection<DrawingWarAirplane, DrawingObjectWarAirplane>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
public void AddSet(string name)
{
if (_warAirplaneStorages.ContainsKey(name))
{
return;
}
_warAirplaneStorages.Add(name, new WarAirplaneGenericCollection<DrawingWarAirplane, DrawingObjectWarAirplane>(_pictureWidth, _pictureHeight));
}
public void DelSet(string name)
{
if (!_warAirplaneStorages.ContainsKey(name))
{
return;
}
_warAirplaneStorages.Remove(name);
}
public WarAirplaneGenericCollection<DrawingWarAirplane, DrawingObjectWarAirplane>? this[string ind]
{
get
{
if (_warAirplaneStorages.ContainsKey(ind))
{
return _warAirplaneStorages[ind];
}
return null;
}
}
public bool SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach(KeyValuePair<string,WarAirplaneGenericCollection<
DrawingWarAirplane,DrawingObjectWarAirplane>> record in _warAirplaneStorages)
{
StringBuilder records = new();
foreach(DrawingWarAirplane? elem in record.Value.GetWarAirplanes)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
}
if(data.Length == 0)
{
throw new Exception("Невалидная операция, нет данных для сохранения");
}
using FileStream fs = new(filename, FileMode.Create);
byte[] info = new UTF8Encoding(true).GetBytes($"WarAirplaneStorage" +
$"{Environment.NewLine}{data}");
fs.Write(info, 0, info.Length);
return true;
}
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new Exception("Файл не найден");
}
string bufferTextFromFile = "";
using (FileStream fs = new(filename, FileMode.Open))
{
byte[] b = new byte[fs.Length];
UTF8Encoding temp = new(true);
while (fs.Read(b,0,b.Length) > 0)
{
bufferTextFromFile += temp.GetString(b);
}
}
var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' },
StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
throw new Exception("Нет данных для загрузки");
}
if (!strs[0].StartsWith("WarAirplaneStorage"))
{
throw new Exception("Неверный формат данных");
}
_warAirplaneStorages.Clear();
foreach (string data in strs)
{
string[] record = data.Split(_separatorForKeyValue,
StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
continue;
}
WarAirplaneGenericCollection<DrawingWarAirplane, DrawingObjectWarAirplane>
collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawingWarAirplane? warAirplane = elem?.CreateDrawingWarAirplane(_separatorForObject, _pictureWidth, _pictureHeight);
if(warAirplane != null)
{
if(collection + warAirplane == -1)
{
return false;
throw new Exception("Ошибка добавления в коллекцию");
}
}
}
_warAirplaneStorages.Add(record[0], collection);
}
return true;
}
}
}

View File

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

View File

@ -0,0 +1,15 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": { "path": "log.txt" }
}
],
"Properties": {
"Application": "Sample"
}
}
}