Merge pull request 'Agliullov D.A Lab Work 2 Advanced' (#2) from Lab2 into Lab1

Reviewed-on: http://student.git.athene.tech/d.agliullov/ISEbd-21_Agliullov.D.A._AirBomber.Advanced/pulls/2
This commit is contained in:
Евгений Эгов 2022-09-30 11:58:02 +04:00
commit 15c46c493f
19 changed files with 1002 additions and 40 deletions

View File

@ -0,0 +1,176 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirBomber
{
internal abstract class AbstractMap
{
private IDrawningObject _drawningObject = null;
private Bitmap? _staticBitMap;
protected int[,] _map = null;
protected int _width;
protected int _height;
protected float _size_x;
protected float _size_y;
protected readonly Random _random = new();
protected readonly int _freeRoad = 0;
protected readonly int _barrier = 1;
public Bitmap CreateMap(int width, int height, IDrawningObject drawningObject)
{
_staticBitMap = null;
_width = width;
_height = height;
_drawningObject = drawningObject;
GenerateMap();
while (!SetObjectOnMap())
{
GenerateMap();
}
return DrawMapWithObject();
}
/// <summary>Проверяет наличие непроходимых участков в заданной области</summary>
/// <param name="area">Заданная область</param>
/// <param name="iBarrier">i-ый индекс первого барьера, который был найден в области</param>
/// <param name="jBarrier">j-ый индекс первого барьера, который был найден в области</param>
/// <returns>Есть ли барьеры</returns>
protected bool BarriersInArea(RectangleF area, ref int iBarrier, ref int jBarrier)
{
if (!(0 < area.Left && area.Right < _width && 0 < area.Top && area.Bottom < _height))
{
return true; // Если область попала за карту, считаем что она столкнулась с барьером
}
int rightArea = (int)Math.Ceiling(area.Right / _size_x);
int bottomArea = (int)Math.Ceiling(area.Bottom / _size_y);
for (int i = (int)(area.Left / _size_x); i < rightArea; i++)
{
for (int j = (int)(area.Top / _size_y); j < bottomArea; j++)
{
if (_map[i, j] == _barrier)
{
iBarrier = i;
jBarrier = j;
return true;
}
}
}
return false;
}
/// <summary>Проверяет наличие непроходимых участков в заданной области</summary>
/// <param name="area">Заданная область</param>
/// <returns>Есть ли барьеры</returns>
protected bool BarriersInArea(RectangleF area)
{
int a = 0, b = 0;
return BarriersInArea(area, ref a, ref b);
}
public Bitmap MoveObject(Direction direction)
{
var rect = _drawningObject.GetCurrentPosition();
var step = _drawningObject.Step;
// Вычисляем области смещения объекта
RectangleF? area = null;
if (direction == Direction.Left)
area = new(rect.Left - step, rect.Top, step, rect.Height);
else if (direction == Direction.Right)
area = new(rect.Right, rect.Top, step, rect.Height);
else if (direction == Direction.Up)
area = new(rect.Left, rect.Top - step, rect.Width, step);
else if (direction == Direction.Down)
area = new(rect.Left, rect.Bottom, rect.Width, step);
if (area.HasValue && !BarriersInArea(area.Value))
{
_drawningObject.MoveObject(direction);
}
return DrawMapWithObject();
}
private bool SetObjectOnMap()
{
if (_drawningObject == null || _map == null)
{
return false;
}
int x = _random.Next(0, 10);
int y = _random.Next(0, 10);
_drawningObject.SetObject(x, y, _width, _height);
// Если натыкаемся на барьер помещаем левый верхний угол чуть ниже этого барьера
// если при этом выходим за карту, пермещаем правый нижный угол чуть выше этого барьера
// если объект выходит за карту, генирируем новые координаты рандомно
int currI = 0, currJ = 0;
var areaObject = _drawningObject.GetCurrentPosition();
int cntOut = 10000; // Количество итераций до выхода из цикла
while (BarriersInArea(areaObject, ref currI, ref currJ) && --cntOut >= 0)
{
if ((currJ + 1) * _size_y + areaObject.Height <= _height)
{
areaObject.Location = new PointF((currI + 1) * _size_x, (currJ + 1) * _size_y);
}
else if ((currI - 1) * _size_x - areaObject.Width >= 0)
{
areaObject = new((currI - 1) * _size_x - areaObject.Width, (currJ - 1) * _size_y - areaObject.Height, areaObject.Width, areaObject.Height);
}
else
{
areaObject.Location = new PointF(_random.Next(0, _width - (int)areaObject.Width),
_random.Next(0, _height - (int)areaObject.Height));
}
}
_drawningObject.SetObject((int)areaObject.X, (int)areaObject.Y, _width, _height);
return cntOut >= 0;
}
/// <summary>
/// Заполняет BitMap для отрисовки статичных объектов. Выполняется один раз при создании карты
/// </summary>
private void DrawMap()
{
if (_staticBitMap != null) return;
_staticBitMap = new(_width, _height);
Graphics gr = Graphics.FromImage(_staticBitMap);
for (int i = 0; i < _map.GetLength(0); ++i)
{
for (int j = 0; j < _map.GetLength(1); ++j)
{
if (_map[i, j] == _freeRoad)
{
DrawRoadPart(gr, i, j);
}
else if (_map[i, j] == _barrier)
{
DrawBarrierPart(gr, i, j);
}
}
}
}
private Bitmap DrawMapWithObject()
{
Bitmap bmp = new(_width, _height);
if (_drawningObject == null || _map == null)
{
return bmp;
}
Graphics gr = Graphics.FromImage(bmp);
if (_staticBitMap == null)
DrawMap();
if (_staticBitMap != null)
gr.DrawImage(_staticBitMap, 0, 0);
_drawningObject.DrawningObject(gr);
return bmp;
}
/// <summary>
/// Генерация карты. При перегрузки определить поля _map, _size_x, _size_y
/// </summary>
protected abstract void GenerateMap();
protected abstract void DrawRoadPart(Graphics g, int i, int j);
protected abstract void DrawBarrierPart(Graphics g, int i, int j);
}
}

View File

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirBomber
{
internal class AirplaneArrowEngines : DrawningAirplaneEngines
{
protected override void DrawEngine(Graphics g, Color colorAirplane, RectangleF rectAroundEngine)
{
var x = rectAroundEngine.X + rectAroundEngine.Width / 4;
g.FillPolygon(new SolidBrush(colorAirplane), new PointF[]
{
new PointF(rectAroundEngine.Left, rectAroundEngine.Top + rectAroundEngine.Height / 2),
new PointF(x, rectAroundEngine.Top),
new PointF(x, rectAroundEngine.Bottom),
});
int margin = 2;
g.FillRectangle(new SolidBrush(colorAirplane),
x , rectAroundEngine.Top + margin,
rectAroundEngine.Right - x, rectAroundEngine.Height - margin * 2);
}
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirBomber
{
internal class AirplaneRectEngines : DrawningAirplaneEngines
{
protected override void DrawEngine(Graphics g, Color colorAirplane, RectangleF rectAroundEngine)
{
g.FillRectangle(new SolidBrush(colorAirplane), rectAroundEngine);
g.FillRectangle(new SolidBrush(Color.Black),
rectAroundEngine.Left, rectAroundEngine.Top, rectAroundEngine.Width / 4, rectAroundEngine.Height);
}
}
}

View File

@ -5,6 +5,7 @@
/// </summary>
internal enum Direction
{
None = 0,
Up = 1,
Down = 2,
Left = 3,

View File

@ -0,0 +1,68 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirBomber
{
internal class DrawningAirBomber : DrawningAirplane
{
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес самолета</param>
/// <param name="bodyColor">Цвет обшивки</param>
/// <param name="dopColor">Дополнительный цвет</param>
/// <param name="hasBombs">Признак наличия бомб</param>
/// <param name="hasFuelTanks">Признак наличия топливных баков</param>
/// <param name="typeAirplaneEngines">Какой будет двигатель самолета. null - двигатели отсутствуют</param>
public DrawningAirBomber(int speed, float weight, Color bodyColor, Color dopColor, bool hasBombs, bool hasFuelTanks, IAirplaneEngines? typeAirplaneEngines = null)
: base(speed, weight, bodyColor, 115, 155, typeAirplaneEngines)
{
Airplane = new EntityAirBomber(speed, weight, bodyColor, dopColor, hasBombs, hasFuelTanks);
}
public override void DrawTransport(Graphics g)
{
if (Airplane is not EntityAirBomber airBomber)
{
return;
}
var x = _startPosX;
var y = _startPosY;
var w = _airplaneWidth;
var h = _airplaneHeight;
Brush brush = new SolidBrush(airBomber.DopColor);
if (airBomber.HasBombs) // Бомбы снизу рисуются сначала
{
DrawBomb(g, airBomber.DopColor, new RectangleF(x + w / 2 - 15, y + h / 2 - 19, 23, 10));
DrawBomb(g, airBomber.DopColor, new RectangleF(x + w / 2 - 15, y + h / 2 + 9, 23, 10));
}
base.DrawTransport(g);
if (airBomber.HasFuelTanks)
{
g.FillEllipse(brush, new RectangleF(x + w / 4, y + h / 2 - 6, w / 2.5f, 12));
}
}
private void DrawBomb(Graphics g, Color colorBomb, RectangleF r)
{
Pen pen = new(colorBomb);
pen.Width = r.Height / 3;
var widthTail = r.Width / 6;
g.FillEllipse(new SolidBrush(colorBomb), r.X, r.Y, r.Width - widthTail, r.Height); // Основание бомбы
// Хвост бомбы
var baseTail = new PointF(r.Right - widthTail, r.Y + r.Height / 2);
g.DrawLine(pen, baseTail, new PointF(r.Right, r.Top));
g.DrawLine(pen, baseTail, new PointF(r.Right, r.Bottom));
}
}
}

View File

@ -8,45 +8,60 @@
/// <summary>
/// Класс-сущность
/// </summary>
public EntityAirplane Airplane { get; private set; }
public EntityAirplane Airplane { get; protected set; }
public DrawningAirplaneEngines DrawningEngines { get; private set; }
public IAirplaneEngines? DrawningEngines { get; private set; }
/// <summary>
/// Левая координата отрисовки самолета
/// </summary>
private float _startPosX;
protected float _startPosX;
/// <summary>
/// Верхняя кооридната отрисовки самолета
/// </summary>
private float _startPosY;
protected float _startPosY;
/// <summary>
/// Ширина окна отрисовки
/// </summary>
private int? _pictureWidth = null;
protected int? _pictureWidth = null;
/// <summary>
/// Высота окна отрисовки
/// </summary>
private int? _pictureHeight = null;
protected int? _pictureHeight = null;
/// <summary>
/// Ширина отрисовки самолета
/// </summary>
private readonly int _airplaneWidth = 110;
protected readonly int _airplaneWidth = 90;
/// <summary>
/// Высота отрисовки самолета
/// </summary>
private readonly int _airplaneHeight = 140;
protected readonly int _airplaneHeight = 105;
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес самолета</param>
/// <param name="bodyColor">Цвет обшивки</param>
public void Init(int speed, float weight, Color bodyColor)
/// <param name="typeAirplaneEngines">Какой будет двигатель самолета. null - двигатели отсутствуют</param>
public DrawningAirplane(int speed, float weight, Color bodyColor, IAirplaneEngines? typeAirplaneEngines = null)
{
Airplane = new EntityAirplane();
Airplane.Init(speed, weight, bodyColor);
DrawningEngines = new();
DrawningEngines.CountEngines = 6;
Airplane = new EntityAirplane(speed, weight, bodyColor);
DrawningEngines = typeAirplaneEngines;
}
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес самолета</param>
/// <param name="bodyColor">Цвет обшивки</param>
/// <param name="airplaneWidth">Ширина отрисовки самолета</param>
/// <param name="airplaneHeight">Высота отрисовки самолета</param>
/// <param name="typeAirplaneEngines">Какой будет двигатель самолета. null - двигатели отсутствуют</param>
protected DrawningAirplane(int speed, float weight, Color bodyColor, int airplaneWidth, int airplaneHeight, IAirplaneEngines? typeAirplaneEngines) :
this(speed, weight, bodyColor, typeAirplaneEngines)
{
_airplaneWidth = airplaneWidth;
_airplaneHeight = airplaneHeight;
}
/// <summary>
/// Установка позиции самолета
@ -116,7 +131,7 @@
/// Отрисовка самолета
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
public virtual void DrawTransport(Graphics g)
{
if (_startPosX < 0 || _startPosY < 0
|| !_pictureHeight.HasValue || !_pictureWidth.HasValue)
@ -156,7 +171,7 @@
// Конец хвоста
g.FillRectangle(BodyColorBrush, x + w - 5, y + 15, 5, h - 30);
// Двигатели
DrawningEngines.DrawEngines(g, Airplane.BodyColor, x + w / 2 - 20, y + h, y, 15);
DrawningEngines?.DrawEngines(g, Airplane.BodyColor, x + w / 2 - 20, y + h, y, 15);
}
@ -198,5 +213,14 @@
_startPosY = _pictureHeight.Value - _airplaneHeight;
}
}
/// <summary>
/// Получение текущей позиции объекта
/// </summary>
/// <returns></returns>
public RectangleF GetCurrentPosition()
{
return new(_startPosX, _startPosY, _airplaneWidth, _airplaneHeight);
}
}
}

View File

@ -9,13 +9,11 @@ namespace AirBomber
/// <summary>
/// Класс-дополнение к самолету отвечающий за число двигателей и их отрисовку
/// </summary>
internal class DrawningAirplaneEngines
internal class DrawningAirplaneEngines : IAirplaneEngines
{
/// <summary>Приватное поле содержащие текущее количество двигателей самолета</summary>
private CountEngines _countEngines;
/// <summary>Получение действительного количества двигателей или установка поддерживаемого числа двигателей</summary>
/// <value>The count engines.</value>
public int CountEngines
{
get => (int)_countEngines;
@ -27,14 +25,6 @@ namespace AirBomber
}
}
/// <summary>Отрисовывает все двигатели на обеих крыльях</summary>
/// <param name="g">The g.</param>
/// <param name="colorEngine">Цвет двигателей.</param>
/// <param name="wingPosX">Позиция крыльев по x. В этой координате будут центры двигателей</param>
/// <param name="leftWingY">Крайняя левая позиция левого крыла по y</param>
/// <param name="rightWingY">Крайняя правая позиция правого крыла по y</param>
/// <param name="widthBodyAirplane">Ширина тела самолета, или расстояние между крыльями.</param>
public void DrawEngines(Graphics g, Color colorEngine, float wingPosX, float leftWingY, float rightWingY, int widthBodyAirplane)
{
float distanceBetweenEngines = (leftWingY - rightWingY - widthBodyAirplane) / 8.0f;
@ -47,7 +37,7 @@ namespace AirBomber
}
}
private void DrawEngine(Graphics g, Color colorAirplane, RectangleF rectAroundEngine)
protected virtual void DrawEngine(Graphics g, Color colorAirplane, RectangleF rectAroundEngine)
{
g.FillEllipse(new SolidBrush(colorAirplane), rectAroundEngine);
g.FillEllipse(new SolidBrush(Color.Black),

View File

@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirBomber
{
internal class DrawningObject : IDrawningObject
{
private DrawningAirplane _airplane;
public DrawningObject(DrawningAirplane airplane)
{
_airplane = airplane;
}
public float Step => _airplane?.Airplane?.Step ?? 0;
public RectangleF GetCurrentPosition()
{
return _airplane.GetCurrentPosition();
}
public void MoveObject(Direction direction)
{
_airplane?.MoveTransport(direction);
}
public void SetObject(int x, int y, int width, int height)
{
_airplane.SetPosition(x, y, width, height);
}
void IDrawningObject.DrawningObject(Graphics g)
{
_airplane.DrawTransport(g);
}
}
}

View File

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

View File

@ -28,7 +28,7 @@
/// <param name="weight"></param>
/// <param name="bodyColor"></param>
/// <returns></returns>
public void Init(int speed, float weight, Color bodyColor)
public EntityAirplane(int speed, float weight, Color bodyColor)
{
Random rnd = new();
Speed = speed <= 0 ? rnd.Next(50, 150) : speed;

View File

@ -33,6 +33,7 @@
this.toolStripStatusLabelSpeed = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStripStatusLabelWeight = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStripStatusLabelBodyColor = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStripStatusCountEngines = new System.Windows.Forms.ToolStripStatusLabel();
this.buttonCreate = new System.Windows.Forms.Button();
this.buttonUp = new System.Windows.Forms.Button();
this.buttonLeft = new System.Windows.Forms.Button();
@ -40,7 +41,7 @@
this.buttonDown = new System.Windows.Forms.Button();
this.countEngineBox = new System.Windows.Forms.NumericUpDown();
this.labelInformCountEngines = new System.Windows.Forms.Label();
this.toolStripStatusCountEngines = new System.Windows.Forms.ToolStripStatusLabel();
this.comboTypeEngines = new System.Windows.Forms.ComboBox();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCar)).BeginInit();
this.statusStrip.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.countEngineBox)).BeginInit();
@ -87,10 +88,16 @@
this.toolStripStatusLabelBodyColor.Size = new System.Drawing.Size(36, 17);
this.toolStripStatusLabelBodyColor.Text = "Цвет:";
//
// toolStripStatusCountEngines
//
this.toolStripStatusCountEngines.Name = "toolStripStatusCountEngines";
this.toolStripStatusCountEngines.Size = new System.Drawing.Size(139, 17);
this.toolStripStatusCountEngines.Text = "Количество двигателей:";
//
// buttonCreate
//
this.buttonCreate.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonCreate.Location = new System.Drawing.Point(244, 390);
this.buttonCreate.Location = new System.Drawing.Point(372, 390);
this.buttonCreate.Name = "buttonCreate";
this.buttonCreate.Size = new System.Drawing.Size(75, 23);
this.buttonCreate.TabIndex = 2;
@ -149,37 +156,45 @@
// countEngineBox
//
this.countEngineBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.countEngineBox.Location = new System.Drawing.Point(142, 390);
this.countEngineBox.Location = new System.Drawing.Point(306, 390);
this.countEngineBox.Maximum = new decimal(new int[] {
10000,
0,
0,
0});
this.countEngineBox.Name = "countEngineBox";
this.countEngineBox.Size = new System.Drawing.Size(96, 23);
this.countEngineBox.Size = new System.Drawing.Size(60, 23);
this.countEngineBox.TabIndex = 7;
//
// labelInformCountEngines
//
this.labelInformCountEngines.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.labelInformCountEngines.AutoSize = true;
this.labelInformCountEngines.Location = new System.Drawing.Point(0, 394);
this.labelInformCountEngines.Location = new System.Drawing.Point(161, 394);
this.labelInformCountEngines.Name = "labelInformCountEngines";
this.labelInformCountEngines.Size = new System.Drawing.Size(139, 15);
this.labelInformCountEngines.TabIndex = 8;
this.labelInformCountEngines.Text = "Количество двигателей:";
//
// toolStripStatusCountEngines
// comboTypeEngines
//
this.toolStripStatusCountEngines.Name = "toolStripStatusCountEngines";
this.toolStripStatusCountEngines.Size = new System.Drawing.Size(139, 17);
this.toolStripStatusCountEngines.Text = "Количество двигателей:";
this.comboTypeEngines.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.comboTypeEngines.FormattingEnabled = true;
this.comboTypeEngines.Items.AddRange(new object[] {
"Закругленный",
"Квадратный",
"Стрелка"});
this.comboTypeEngines.Location = new System.Drawing.Point(12, 390);
this.comboTypeEngines.Name = "comboTypeEngines";
this.comboTypeEngines.Size = new System.Drawing.Size(143, 23);
this.comboTypeEngines.TabIndex = 9;
//
// FormAirBomber
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.comboTypeEngines);
this.Controls.Add(this.labelInformCountEngines);
this.Controls.Add(this.countEngineBox);
this.Controls.Add(this.buttonDown);
@ -215,5 +230,6 @@
private NumericUpDown countEngineBox;
private Label labelInformCountEngines;
private ToolStripStatusLabel toolStripStatusCountEngines;
private ComboBox comboTypeEngines;
}
}

View File

@ -25,9 +25,23 @@ namespace AirBomber
/// <param name="e"></param>
private void ButtonCreate_Click(object sender, EventArgs e)
{
IAirplaneEngines? typeAirplaneEngines = null;
switch (comboTypeEngines.Text)
{
case "Êâàäðàòíûé":
typeAirplaneEngines = new AirplaneRectEngines();
break;
case "Ñòðåëêà":
typeAirplaneEngines = new AirplaneArrowEngines();
break;
default:
typeAirplaneEngines = new DrawningAirplaneEngines();
break;
}
Random rnd = new();
_airplane = new DrawningAirplane();
_airplane.Init(rnd.Next(100, 300), rnd.Next(1000, 2000), Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256)));
_airplane = new DrawningAirplane(rnd.Next(100, 300), rnd.Next(1000, 2000),
Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256)),
typeAirplaneEngines);
_airplane.DrawningEngines.CountEngines = (int)countEngineBox.Value;
_airplane.SetPosition(rnd.Next(10, 100), rnd.Next(10, 100), pictureBoxCar.Width, pictureBoxCar.Height);
toolStripStatusLabelSpeed.Text = $"Ñêîðîñòü: {_airplane.Airplane.Speed}";

208
AirBomber/AirBomber/FormMap.Designer.cs generated Normal file
View File

@ -0,0 +1,208 @@
namespace AirBomber
{
partial class FormMap
{
/// <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.pictureBoxCar = new System.Windows.Forms.PictureBox();
this.statusStrip = new System.Windows.Forms.StatusStrip();
this.toolStripStatusLabelSpeed = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStripStatusLabelWeight = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStripStatusLabelBodyColor = new System.Windows.Forms.ToolStripStatusLabel();
this.buttonCreate = new System.Windows.Forms.Button();
this.buttonUp = new System.Windows.Forms.Button();
this.buttonLeft = new System.Windows.Forms.Button();
this.buttonRight = new System.Windows.Forms.Button();
this.buttonDown = new System.Windows.Forms.Button();
this.buttonCreateModif = new System.Windows.Forms.Button();
this.comboBoxSelectorMap = new System.Windows.Forms.ComboBox();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCar)).BeginInit();
this.statusStrip.SuspendLayout();
this.SuspendLayout();
//
// pictureBoxCar
//
this.pictureBoxCar.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBoxCar.Location = new System.Drawing.Point(0, 0);
this.pictureBoxCar.Name = "pictureBoxCar";
this.pictureBoxCar.Size = new System.Drawing.Size(800, 428);
this.pictureBoxCar.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pictureBoxCar.TabIndex = 0;
this.pictureBoxCar.TabStop = false;
//
// statusStrip
//
this.statusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripStatusLabelSpeed,
this.toolStripStatusLabelWeight,
this.toolStripStatusLabelBodyColor});
this.statusStrip.Location = new System.Drawing.Point(0, 428);
this.statusStrip.Name = "statusStrip";
this.statusStrip.Size = new System.Drawing.Size(800, 22);
this.statusStrip.TabIndex = 1;
//
// toolStripStatusLabelSpeed
//
this.toolStripStatusLabelSpeed.Name = "toolStripStatusLabelSpeed";
this.toolStripStatusLabelSpeed.Size = new System.Drawing.Size(62, 17);
this.toolStripStatusLabelSpeed.Text = "Скорость:";
//
// toolStripStatusLabelWeight
//
this.toolStripStatusLabelWeight.Name = "toolStripStatusLabelWeight";
this.toolStripStatusLabelWeight.Size = new System.Drawing.Size(29, 17);
this.toolStripStatusLabelWeight.Text = "Вес:";
//
// toolStripStatusLabelBodyColor
//
this.toolStripStatusLabelBodyColor.Name = "toolStripStatusLabelBodyColor";
this.toolStripStatusLabelBodyColor.Size = new System.Drawing.Size(36, 17);
this.toolStripStatusLabelBodyColor.Text = "Цвет:";
//
// buttonCreate
//
this.buttonCreate.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonCreate.Location = new System.Drawing.Point(12, 390);
this.buttonCreate.Name = "buttonCreate";
this.buttonCreate.Size = new System.Drawing.Size(75, 23);
this.buttonCreate.TabIndex = 2;
this.buttonCreate.Text = "Создать";
this.buttonCreate.UseVisualStyleBackColor = true;
this.buttonCreate.Click += new System.EventHandler(this.ButtonCreate_Click);
//
// buttonUp
//
this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonUp.BackgroundImage = global::AirBomber.Properties.Resources.arrowUp;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonUp.Location = new System.Drawing.Point(722, 350);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(30, 30);
this.buttonUp.TabIndex = 3;
this.buttonUp.UseVisualStyleBackColor = true;
this.buttonUp.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonLeft
//
this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonLeft.BackgroundImage = global::AirBomber.Properties.Resources.arrowLeft;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonLeft.Location = new System.Drawing.Point(686, 386);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(30, 30);
this.buttonLeft.TabIndex = 4;
this.buttonLeft.UseVisualStyleBackColor = true;
this.buttonLeft.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonRight
//
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::AirBomber.Properties.Resources.arrowRight;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonRight.Location = new System.Drawing.Point(758, 386);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(30, 30);
this.buttonRight.TabIndex = 5;
this.buttonRight.UseVisualStyleBackColor = true;
this.buttonRight.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonDown
//
this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDown.BackgroundImage = global::AirBomber.Properties.Resources.arrowDown;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonDown.Location = new System.Drawing.Point(722, 386);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(30, 30);
this.buttonDown.TabIndex = 6;
this.buttonDown.UseVisualStyleBackColor = true;
this.buttonDown.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonCreateModif
//
this.buttonCreateModif.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonCreateModif.Location = new System.Drawing.Point(104, 390);
this.buttonCreateModif.Name = "buttonCreateModif";
this.buttonCreateModif.Size = new System.Drawing.Size(110, 23);
this.buttonCreateModif.TabIndex = 7;
this.buttonCreateModif.Text = "Модификация";
this.buttonCreateModif.UseVisualStyleBackColor = true;
this.buttonCreateModif.Click += new System.EventHandler(this.ButtonCreateModif_Click);
//
// comboBoxSelectorMap
//
this.comboBoxSelectorMap.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxSelectorMap.FormattingEnabled = true;
this.comboBoxSelectorMap.Items.AddRange(new object[] {
"Простая карта",
"Карта со стенами"});
this.comboBoxSelectorMap.Location = new System.Drawing.Point(12, 12);
this.comboBoxSelectorMap.Name = "comboBoxSelectorMap";
this.comboBoxSelectorMap.Size = new System.Drawing.Size(121, 23);
this.comboBoxSelectorMap.TabIndex = 8;
this.comboBoxSelectorMap.SelectedIndexChanged += new System.EventHandler(this.ComboBoxSelectorMap_SelectedIndexChanged);
//
// FormMap
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.comboBoxSelectorMap);
this.Controls.Add(this.buttonCreateModif);
this.Controls.Add(this.buttonDown);
this.Controls.Add(this.buttonRight);
this.Controls.Add(this.buttonLeft);
this.Controls.Add(this.buttonUp);
this.Controls.Add(this.buttonCreate);
this.Controls.Add(this.pictureBoxCar);
this.Controls.Add(this.statusStrip);
this.Name = "FormMap";
this.Text = "Карта";
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCar)).EndInit();
this.statusStrip.ResumeLayout(false);
this.statusStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private PictureBox pictureBoxCar;
private StatusStrip statusStrip;
private ToolStripStatusLabel toolStripStatusLabelSpeed;
private ToolStripStatusLabel toolStripStatusLabelWeight;
private ToolStripStatusLabel toolStripStatusLabelBodyColor;
private Button buttonCreate;
private Button buttonUp;
private Button buttonLeft;
private Button buttonRight;
private Button buttonDown;
private Button buttonCreateModif;
private ComboBox comboBoxSelectorMap;
}
}

View File

@ -0,0 +1,96 @@
using AirBomber;
namespace AirBomber
{
public partial class FormMap : Form
{
private AbstractMap _abstractMap;
public FormMap()
{
InitializeComponent();
_abstractMap = new SimpleMap();
}
/// <summary>
/// Заполнение информации по объекту
/// </summary>
/// <param name="car"></param>
private void SetData(DrawningAirplane car)
{
toolStripStatusLabelSpeed.Text = $"Скорость: {car.Airplane.Speed}";
toolStripStatusLabelWeight.Text = $"Вес: {car.Airplane.Weight}";
toolStripStatusLabelBodyColor.Text = $"Цвет: {car.Airplane.BodyColor.Name}";
pictureBoxCar.Image = _abstractMap.CreateMap(pictureBoxCar.Width, pictureBoxCar.Height,
new DrawningObject(car));
}
/// <summary>
/// Обработка нажатия кнопки "Создать"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreate_Click(object sender, EventArgs e)
{
Random rnd = new();
var car = new DrawningAirplane(rnd.Next(100, 300), rnd.Next(1000, 2000), Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256)));
SetData(car);
}
/// <summary>
/// Изменение размеров формы
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
//получаем имя кнопки
string name = ((Button)sender)?.Name ?? string.Empty;
Direction dir = Direction.None;
switch (name)
{
case "buttonUp":
dir = Direction.Up;
break;
case "buttonDown":
dir = Direction.Down;
break;
case "buttonLeft":
dir = Direction.Left;
break;
case "buttonRight":
dir = Direction.Right;
break;
}
pictureBoxCar.Image = _abstractMap?.MoveObject(dir);
}
/// <summary>
/// Обработка нажатия кнопки "Модификация"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateModif_Click(object sender, EventArgs e)
{
Random rnd = new();
var car = new DrawningAirBomber(rnd.Next(100, 300), rnd.Next(1000, 2000),
Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256)),
Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256)),
Convert.ToBoolean(rnd.Next(0, 2)), Convert.ToBoolean(rnd.Next(0, 2)));
SetData(car);
}
/// <summary>
/// Смена карты
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ComboBoxSelectorMap_SelectedIndexChanged(object sender, EventArgs e)
{
switch (comboBoxSelectorMap.Text)
{
case "Простая карта":
_abstractMap = new SimpleMap();
break;
case "Карта со стенами":
_abstractMap = new WallMap();
break;
}
}
}
}

View File

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

View File

@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirBomber
{
internal interface IAirplaneEngines
{
/// <summary>Получение действительного количества двигателей или установка поддерживаемого числа двигателей</summary>
/// <value>The count engines.</value>
int CountEngines { get; set; }
/// <summary>Отрисовывает все двигатели на обеих крыльях</summary>
/// <param name="g">The g.</param>
/// <param name="colorEngine">Цвет двигателей.</param>
/// <param name="wingPosX">Позиция крыльев по x. В этой координате будут центры двигателей</param>
/// <param name="leftWingY">Крайняя левая позиция левого крыла по y</param>
/// <param name="rightWingY">Крайняя правая позиция правого крыла по y</param>
/// <param name="widthBodyAirplane">Ширина тела самолета, или расстояние между крыльями.</param>
void DrawEngines(Graphics g, Color colorEngine, float wingPosX, float leftWingY, float rightWingY, int widthBodyAirplane);
}
}

View File

@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirBomber
{
/// <summary>
/// Интерфейс для работы с объектом, прорисовываемым на форме
/// </summary>
internal interface IDrawningObject
{
/// <summary>
/// Шаг перемещения объекта
/// </summary>
public float Step { get; }
/// <summary>
/// Установка позиции объекта
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
/// <param name="width">Ширина полотна</param>
/// <param name="height">Высота полотна</param>
void SetObject(int x, int y, int width, int height);
/// <summary>
/// Изменение направления пермещения объекта
/// </summary>
/// <param name="direction">Направление</param>
/// <returns></returns>
void MoveObject(Direction direction);
/// <summary>
/// Отрисовка объекта
/// </summary>
/// <param name="g"></param>
void DrawningObject(Graphics g);
/// <summary>
/// Получение текущей позиции объекта
/// </summary>
/// <returns></returns>
RectangleF GetCurrentPosition();
}
}

View File

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

View File

@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirBomber
{
internal class WallMap : AbstractMap
{
/// <summary>
/// Цвет участка закрытого
/// </summary>
private readonly Brush barrierColor = new SolidBrush(Color.Brown);
/// <summary>
/// Цвет участка открытого
/// </summary>
private readonly Brush roadColor = new SolidBrush(Color.LightPink);
protected override void DrawBarrierPart(Graphics g, int i, int j)
{
g.FillPolygon(barrierColor, new PointF[]
{
new PointF(i * _size_x, j * _size_y),
new PointF((i + 1) * _size_x, j * _size_y),
new PointF((i + 1) * _size_x - _size_x / 4, (j + 1) * _size_y - _size_y / 2),
new PointF((i + 1) * _size_x, (j + 1) * _size_y),
new PointF(i * _size_x, (j + 1) * _size_y),
new PointF(i * _size_x + _size_x / 4, (j + 1) * _size_y - _size_y / 2),
});
}
protected override void DrawRoadPart(Graphics g, int i, int j)
{
g.FillRectangle(roadColor, i * _size_x, j * _size_y, (i + 1) * _size_x, (j + 1) * _size_y);
}
protected override void GenerateMap()
{
_map = new int[120, 120];
var minSize = Math.Min(_map.GetLength(0), _map.GetLength(1));
_size_x = (float)_width / _map.GetLength(0);
_size_y = (float)_height / _map.GetLength(1);
for (int i = 0; i < _map.GetLength(0); ++i)
{
for (int j = 0; j < _map.GetLength(1); ++j)
{
_map[i, j] = _freeRoad;
}
}
for (var i = 0; i < 10; i++)
{
var lengthWall = _random.Next(3, minSize / 2);
var incX = _random.Next(0, 2);
var incY = 1 - incX;
var left = _random.Next(0, _map.GetLength(0) - lengthWall);
var top = _random.Next(0, _map.GetLength(1) - lengthWall);
for (var j = 0; j < lengthWall; j++)
{
_map[left + incX * j, top + incY * j] = _barrier;
}
}
}
}
}