Compare commits

..

15 Commits

Author SHA1 Message Date
platoff aeeee
03dcb34d30 Готовая 3 лаба 2023-11-07 16:56:14 +04:00
platoff aeeee
338ff227a5 Готовая 3 лаба 2023-11-07 16:50:01 +04:00
platoff aeeee
e8df20e0eb Готовая 3 лаба 2023-10-25 10:40:17 +04:00
platoff aeeee
28f3d56a17 правки 3 лаба 2023-10-24 23:44:03 +04:00
platoff aeeee
25b4c0cd84 Готовая 2 лаба 2023-10-11 10:55:24 +04:00
platoff aeeee
205635a1f8 Правки2лаб 2023-10-11 10:43:28 +04:00
platoff aeeee
6412d03510 Правки2лаб 2023-10-11 10:41:13 +04:00
platoff aeeee
35ef737015 Правки 2 лабы 2023-10-11 09:18:45 +04:00
platoff aeeee
7293c69407 Правки 2023-10-11 09:18:35 +04:00
platoff aeeee
083ffec901 Правки 2лаб 2023-10-10 23:57:24 +04:00
platoff aeeee
a52eb31b45 Правки лаб2 2023-10-10 23:46:42 +04:00
platoff aeeee
0b3396d17f перенос 2 лабы 2023-10-03 19:51:48 +04:00
platoff aeeee
a7f1fc2910 Готовая 1 лаба 2023-09-27 09:20:00 +04:00
platoff aeeee
02c4fa2ec2 Правки 2023-09-26 23:13:18 +04:00
platoff aeeee
cd60cbbe7f Перенесение проекта 2023-09-26 17:01:06 +04:00
23 changed files with 1452 additions and 351 deletions

View File

@ -6,27 +6,12 @@ using System.Threading.Tasks;
namespace Tank
{
/// <summary>
/// Направление перемещения
/// </summary>
public enum Direction
{
/// <summary>
/// Вверх
///
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}
}

View File

@ -1,223 +0,0 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tank
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningTank
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityTank? EntityTank { get; private set; }
/// <summary>
/// Ширина окна
/// </summary>
private int _pictureWidth = 900;
/// <summary>
/// Высота окна
/// </summary>
private int _pictureHeight = 500;
/// <summary>
/// Левая координата прорисовки автомобиля
/// </summary>
private int _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки автомобиля
/// </summary>
private int _startPosY;
/// <summary>
/// Ширина прорисовки автомобиля
/// </summary>
private readonly int _tankWidth = 110;
/// <summary>
/// Высота прорисовки автомобиля
/// </summary>
private readonly int _tankHeight = 60;
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет кузова</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="bodyKit">Признак наличия обвеса</param>
/// <param name="trunk">Признак наличия антикрыла</param>
/// <param name="sportLine">Признак наличия гоночной полосы</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <returns>true - объект создан, false - проверка не пройдена,
/// нельзя создать объект в этих размерах</returns>
public bool Init(int speed, double weight, Color bodyColor, Color
additionalColor, bool bodyKit, bool trunk, bool sportLine, int width, int height)
{
// TODO: проверки
if (width > _tankWidth && height > _tankHeight && speed > 0 && weight > 0)
{
_pictureWidth = width;
_pictureHeight = height;
EntityTank = new EntityTank();
EntityTank.Init(speed, weight, bodyColor, additionalColor,
bodyKit, trunk, sportLine);
return true;
}
return false;
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
// проверки
if (x >= 0 && x + _tankWidth <= _pictureWidth &&
y >= 0 && y + _tankHeight <= _pictureHeight)
{
_startPosX = x;
_startPosY = y;
}
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
public void MoveTransport(Direction direction)
{
if (EntityTank == null)
{
return;
}
switch (direction)
{
//влево
case Direction.Left:
if (_startPosX - EntityTank.Step > 0)
{
_startPosX -= (int)EntityTank.Step;
}
break;
//вверх
case Direction.Up:
if (_startPosY - EntityTank.Step > 0)
{
_startPosY -= (int)EntityTank.Step;
}
break;
// вправо
case Direction.Right:
if (_startPosX + EntityTank.Step + _tankWidth < _pictureWidth)
{
_startPosX += (int)EntityTank.Step;
}
break;
//вниз
case Direction.Down:
if (_startPosY + EntityTank.Step + _tankHeight < _pictureHeight)
{
_startPosY += (int)EntityTank.Step;
}
break;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
{
if (EntityTank == null)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new
SolidBrush(EntityTank.AdditionalColor);
// гусеница
Rectangle Caterpillar = new Rectangle(_startPosX + 2, _startPosY + 35, 16, 22);
float startAngle_Caterpillar = 90;
float sweepAngle_Caterpillar = 180;
g.DrawArc(pen, Caterpillar, startAngle_Caterpillar, sweepAngle_Caterpillar);
Rectangle Caterpillar2 = new Rectangle(_startPosX + 102, _startPosY + 35, 16, 22);
float startAngle_Caterpillar2 = 270;
float sweepAngle_Caterpillar2 = 180;
g.DrawArc(pen, Caterpillar2, startAngle_Caterpillar2, sweepAngle_Caterpillar2);
Point startPoint = new Point(_startPosX + 10, _startPosY + 58);
Point endPoint = new Point(_startPosX + 110, _startPosY + 58);
g.DrawLine(pen, startPoint, endPoint);
// колеса
Brush brBlack = new SolidBrush(Color.Black);
g.FillEllipse(brBlack, _startPosX + 95, _startPosY + 35, 20, 20);
g.FillEllipse(brBlack, _startPosX + 5, _startPosY + 35, 20, 20);
// колеса снизу поменьше
g.FillEllipse(brBlack, _startPosX + 25, _startPosY + 47, 10, 10);
g.FillEllipse(brBlack, _startPosX + 45, _startPosY + 47, 10, 10);
g.FillEllipse(brBlack, _startPosX + 65, _startPosY + 47, 10, 10);
g.FillEllipse(brBlack, _startPosX + 85, _startPosY + 47, 10, 10);
// колеса сверху
g.FillEllipse(brBlack, _startPosX + 35, _startPosY + 32, 10, 10);
g.FillEllipse(brBlack, _startPosX + 55, _startPosY + 32, 10, 10);
g.FillEllipse(brBlack, _startPosX + 75, _startPosY + 32, 10, 10);
//кузов
Brush br = new SolidBrush(EntityTank.BodyColor);
g.FillRectangle(br, _startPosX + 5, _startPosY + 17, 110, 18);
g.FillRectangle(br, _startPosX + 30, _startPosY, 50, 15);
// пулемет
g.FillRectangle(br, _startPosX + 80, _startPosY + 3, 25, 5);
// зенитный пулемет на башне
g.FillRectangle(br, _startPosX + 40, _startPosY - 10, 20, 5);
g.FillRectangle(brBlack, _startPosX + 50, _startPosY - 5, 5, 5);
g.FillRectangle(brBlack, _startPosX + 55, _startPosY - 10, 5, 10);
g.FillRectangle(brBlack, _startPosX + 52, _startPosY - 7, 3, 2);
//выделяем рамкой весь танк
g.DrawRectangle(pen, _startPosX + 5, _startPosY + 17, 110, 18);
g.DrawRectangle(pen, _startPosX + 30, _startPosY, 50, 15);
g.DrawRectangle(pen, _startPosX + 80, _startPosY + 3, 25, 5);
g.DrawRectangle(pen, _startPosX + 40, _startPosY - 10, 20, 5);
// обвесы
if (EntityTank.BodyKit)
{
Brush brAdd = new SolidBrush(EntityTank.AdditionalColor);
g.FillRectangle(brAdd, _startPosX + 5, _startPosY + 17, 20, 18);
g.FillRectangle(brAdd, _startPosX + 95, _startPosY + 17, 20, 18);
g.DrawRectangle(pen, _startPosX + 5, _startPosY + 17, 20, 18);
g.DrawRectangle(pen, _startPosX + 95, _startPosY + 17, 20, 18);
g.FillRectangle(brAdd, _startPosX + 100, _startPosY + 4, 5, 4);
}
//// спортивная линия
//if (EntityTank.SportLine)
//{
// g.FillRectangle(additionalBrush, _startPosX + 75,
// _startPosY + 23, 25, 15);
// g.FillRectangle(additionalBrush, _startPosX + 35,
// _startPosY + 23, 35, 15);
// g.FillRectangle(additionalBrush, _startPosX + 10,
// _startPosY + 23, 20, 15);
//}
// багажник
if (EntityTank.Trunk)
{
g.FillRectangle(additionalBrush, _startPosX + 23, _startPosY + 4, 8, 10);
g.DrawRectangle(pen, _startPosX + 23, _startPosY + 4 , 8, 10);
}
}
}
}

View File

@ -0,0 +1,214 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tank.Entites;
using Tank.MovementStrategy;
namespace Tank.DrawingObjects
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawingArmoredCar
{
public IMoveableObject GetMoveableObject => new DrawingObjectArmoredCar(this);
/// <summary>
/// Класс-сущность
/// </summary>
public EntityArmoredCar? Tank { get; protected set; }
/// <summary>
/// Координата X объекта
/// </summary>
public int GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _ArmoredcarWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _ArmoredcarHeight;
/// <summary>
/// Проверка, что объект может переместится по указанному направлению
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - можно переместится по указанному
/// направлению</returns>
public bool CanMove(Direction direction)
{
if (Tank == null)
{
return false;
}
return direction switch
{
Direction.Left => _startPosX - Tank.Step > 0,
Direction.Up => _startPosY - Tank.Step > 0,
Direction.Right => _startPosX + Tank.Step < _pictureWidth - _ArmoredcarWidth, //вниз
Direction.Down => _startPosY + Tank.Step < _pictureHeight - _ArmoredcarHeight,
_ => false,
};
}
/// <summary>
/// Ширина окна
/// </summary>
private int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int _pictureHeight;
/// <summary>
/// Левая координата прорисовки автомобиля
/// </summary>
protected int _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки автомобиля
/// </summary>
protected int _startPosY;
/// <summary>
/// Ширина прорисовки автомобиля
/// </summary>
protected readonly int _ArmoredcarWidth = 150;
/// <summary>
/// Высота прорисовки автомобиля
/// </summary>
protected readonly int _ArmoredcarHeight = 65;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public DrawingArmoredCar(int speed, double weight, Color bodyColor, int
width, int height)
{
_pictureWidth = width;
_pictureHeight = height;
if (_pictureHeight < _ArmoredcarHeight || _pictureWidth < _ArmoredcarWidth)
{
return;
}
Tank = new EntityArmoredCar(speed, weight, bodyColor);
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <param name="carWidth">Ширина прорисовки автомобиля</param>
/// <param name="carHeight">Высота прорисовки автомобиля</param>
protected DrawingArmoredCar(int speed, double weight, Color bodyColor, int
width, int height, int carWidth, int carHeight)
{
_pictureWidth = width;
_pictureHeight = height;
_ArmoredcarWidth = _ArmoredcarWidth;
_ArmoredcarHeight = _ArmoredcarHeight;
if (_pictureHeight < _ArmoredcarHeight || _pictureWidth < _ArmoredcarWidth) {
return;
}
Tank = new EntityArmoredCar(speed, weight, bodyColor);
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
if (x <0 || x > _pictureHeight - _ArmoredcarHeight)
{
x = 0;
}
if (y < 0 || y > _pictureWidth - _ArmoredcarWidth)
{
y = 0;
}
_startPosX = x;
_startPosY = y;
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
public void MoveTransport(Direction direction)
{
if (Tank == null)
{
return;
}
switch (direction)
{
//влево
case Direction.Left:
if (_startPosX - Tank.Step > 0)
{
_startPosX -= (int)Tank.Step;
}
break;
//вверх
case Direction.Up:
if (_startPosY - Tank.Step > 0)
{
_startPosY -= (int)Tank.Step;
}
break;
// вправо
case Direction.Right:
if (_startPosX + Tank.Step + _ArmoredcarWidth < _pictureWidth)
{
_startPosX += (int)Tank.Step;
}
break;
//вниз
case Direction.Down:
if (_startPosY + Tank.Step + _ArmoredcarHeight < _pictureHeight)
{
_startPosY += (int)Tank.Step;
}
break;
}
}
//}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public virtual void DrawTransport(Graphics g)
{
if (Tank == null)
{
return;
}
Brush BrushRandom = new SolidBrush(Tank?.BodyColor ?? Color.Black);
//кузов
Brush br = new SolidBrush(Tank.BodyColor);
g.FillRectangle(br, _startPosX + 5, _startPosY + 17, 110, 18);
g.FillRectangle(br, _startPosX + 30, _startPosY + 3, 50, 13);
// колеса
Brush brBlack = new SolidBrush(Color.Black);
g.FillEllipse(brBlack, _startPosX + 95, _startPosY + 35, 20, 20);
g.FillEllipse(brBlack, _startPosX + 5, _startPosY + 35, 20, 20);
}
}
}

View File

@ -0,0 +1,127 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tank.Entites;
namespace Tank.DrawingObjects
{
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
public class DrawingTank : DrawingArmoredCar
{
/// Конструктор
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="bodyKit">Признак наличия обвеса</param>
/// <param name="wing">Признак наличия антикрыла</param>
/// <param name="sportLine">Признак наличия гоночной полосы</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public DrawingTank(int speed, double weight, Color bodyColor, Color
additionalColor, bool bodyKit, bool wing, bool sportLine, int width, int height) :
base(speed, weight, bodyColor, width, height, 110, 60)
{
if (Tank != null)
{
Tank = new EntityTank(speed, weight, bodyColor,
additionalColor, bodyKit, wing, sportLine);
}
}
public override void DrawTransport(Graphics g)
{
if (Tank is not EntityTank ArmoredCar)
{
return;
}
base.DrawTransport(g);
Pen pen = new(Color.Black);
Brush additionalBrush = new
SolidBrush(ArmoredCar.AdditionalColor);
// гусеница
Rectangle Caterpillar = new Rectangle(_startPosX + 2, _startPosY + 35, 16, 22);
float startAngle_Caterpillar = 90;
float sweepAngle_Caterpillar = 180;
g.DrawArc(pen, Caterpillar, startAngle_Caterpillar, sweepAngle_Caterpillar);
Rectangle Caterpillar2 = new Rectangle(_startPosX + 102, _startPosY + 35, 16, 22);
float startAngle_Caterpillar2 = 270;
float sweepAngle_Caterpillar2 = 180;
g.DrawArc(pen, Caterpillar2, startAngle_Caterpillar2, sweepAngle_Caterpillar2);
Point startPoint = new Point(_startPosX + 10, _startPosY + 58);
Point endPoint = new Point(_startPosX + 110, _startPosY + 58);
g.DrawLine(pen, startPoint, endPoint);
// колеса
Brush brBlack = new SolidBrush(Color.Black);
g.FillEllipse(brBlack, _startPosX + 95, _startPosY + 35, 20, 20);
g.FillEllipse(brBlack, _startPosX + 5, _startPosY + 35, 20, 20);
// колеса снизу поменьше
g.FillEllipse(brBlack, _startPosX + 25, _startPosY + 47, 10, 10);
g.FillEllipse(brBlack, _startPosX + 45, _startPosY + 47, 10, 10);
g.FillEllipse(brBlack, _startPosX + 65, _startPosY + 47, 10, 10);
g.FillEllipse(brBlack, _startPosX + 85, _startPosY + 47, 10, 10);
// колеса сверху
g.FillEllipse(brBlack, _startPosX + 35, _startPosY + 32, 10, 10);
g.FillEllipse(brBlack, _startPosX + 55, _startPosY + 32, 10, 10);
g.FillEllipse(brBlack, _startPosX + 75, _startPosY + 32, 10, 10);
//кузов
Brush br = new SolidBrush(ArmoredCar.BodyColor);
g.FillRectangle(br, _startPosX + 5, _startPosY + 17, 110, 18);
g.FillRectangle(br, _startPosX + 30, _startPosY, 50, 15);
// пулемет
g.FillRectangle(br, _startPosX + 80, _startPosY + 3, 25, 5);
// зенитный пулемет на башне
g.FillRectangle(br, _startPosX + 40, _startPosY - 10, 20, 5);
g.FillRectangle(brBlack, _startPosX + 50, _startPosY - 5, 5, 5);
g.FillRectangle(brBlack, _startPosX + 55, _startPosY - 10, 5, 10);
g.FillRectangle(brBlack, _startPosX + 52, _startPosY - 7, 3, 2);
//выделяем рамкой весь танк
g.DrawRectangle(pen, _startPosX + 5, _startPosY + 17, 110, 18);
g.DrawRectangle(pen, _startPosX + 30, _startPosY, 50, 15);
g.DrawRectangle(pen, _startPosX + 80, _startPosY + 3, 25, 5);
g.DrawRectangle(pen, _startPosX + 40, _startPosY - 10, 20, 5);
// обвесы
if (ArmoredCar.BodyKit)
{
Brush brAdd = new SolidBrush(ArmoredCar.AdditionalColor);
g.FillRectangle(brAdd, _startPosX + 5, _startPosY + 17, 20, 18);
g.FillRectangle(brAdd, _startPosX + 95, _startPosY + 17, 20, 18);
g.DrawRectangle(pen, _startPosX + 5, _startPosY + 17, 20, 18);
g.DrawRectangle(pen, _startPosX + 95, _startPosY + 17, 20, 18);
g.FillRectangle(brAdd, _startPosX + 100, _startPosY + 4, 5, 4);
}
// линия
if (ArmoredCar.Line)
{
g.FillRectangle(additionalBrush, _startPosX + 75,
_startPosY + 23, 25, 15);
g.FillRectangle(additionalBrush, _startPosX + 35,
_startPosY + 23, 35, 15);
g.FillRectangle(additionalBrush, _startPosX + 10,
_startPosY + 23, 20, 15);
}
// багажник
if (ArmoredCar.Trunk)
{
g.FillRectangle(additionalBrush, _startPosX + 23, _startPosY + 4, 8, 10);
g.DrawRectangle(pen, _startPosX + 23, _startPosY + 4, 8, 10);
}
}
}
}

View File

@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tank.Entites
{
/// <summary>
/// Класс-сущность "Бронированная машина"
/// </summary>
public class EntityArmoredCar
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; set; }
/// <summary>
/// Шаг перемещения автомобиля
/// </summary>
public double Step => (double)Speed * 300 / Weight;
/// <summary>
/// Конструктор с параметрами
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Основной цвет</param>
public EntityArmoredCar(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}
}

View File

@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tank.Entites;
namespace Tank.Entites
{
public class EntityTank : EntityArmoredCar
{
public int Speed { get; private set; }
public Color AdditionalColor { get; private set; }
public bool BodyKit { get; private set; }
public bool Trunk { get; private set; }
public bool Line { get; private set; }
/// Шаг перемещения танка
/// Инициализация полей объекта-класса спортивного автомобиля
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес Танка</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="bodyKit">Признак наличия обвеса</param>
/// <param name="trunk">Признак наличия багажника</param>
/// <param name="line">Признак наличия гоночной полосы</param>
public EntityTank(int speed, double weight, Color bodyColor, Color
additionalColor, bool bodyKit, bool trunk, bool line) : base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
BodyKit = bodyKit;
Trunk = trunk;
Line = line;
}
}
}

View File

@ -1,66 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tank
{
public class EntityTank
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; }
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
public Color AdditionalColor { get; private set; }
/// <summary>
/// Признак (опция) наличия обвеса
/// </summary>
public bool BodyKit { get; private set; }
/// <summary>
/// Признак (опция) наличия Багажника
/// </summary>
public bool Trunk { get; private set; }
/// <summary>
/// Признак (опция) наличия гоночной полосы
/// </summary>
public bool SportLine { get; private set; }
/// <summary>
/// Шаг перемещения танка
/// </summary>
public double Step => (double)Speed * 200 / Weight;
/// <summary>
/// Инициализация полей объекта-класса спортивного автомобиля
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес Танка</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="bodyKit">Признак наличия обвеса</param>
/// <param name="trunk">Признак наличия багажника</param>
/// <param name="sportLine">Признак наличия гоночной полосы</param>
public void Init(int speed, double weight, Color bodyColor, Color
additionalColor, bool bodyKit, bool trunk, bool sportLine)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor;
BodyKit = bodyKit;
Trunk = trunk;
SportLine = sportLine;
}
}
}

View File

@ -0,0 +1,124 @@
namespace Tank
{
partial class FormArmoredCarCollection
{
/// <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.groupBox1 = new System.Windows.Forms.GroupBox();
this.maskedTextBoxNumber = new System.Windows.Forms.MaskedTextBox();
this.ButtonRefreshCollection = new System.Windows.Forms.Button();
this.ButtonRemoveArmoredCar = new System.Windows.Forms.Button();
this.ButtonAddArmoredCar = new System.Windows.Forms.Button();
this.pictureBoxCollection = new System.Windows.Forms.PictureBox();
this.groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).BeginInit();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.maskedTextBoxNumber);
this.groupBox1.Controls.Add(this.ButtonRefreshCollection);
this.groupBox1.Controls.Add(this.ButtonRemoveArmoredCar);
this.groupBox1.Controls.Add(this.ButtonAddArmoredCar);
this.groupBox1.Location = new System.Drawing.Point(579, 12);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(200, 426);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Инструменты";
//
// maskedTextBoxNumber
//
this.maskedTextBoxNumber.Location = new System.Drawing.Point(36, 85);
this.maskedTextBoxNumber.Name = "maskedTextBoxNumber";
this.maskedTextBoxNumber.Size = new System.Drawing.Size(129, 23);
this.maskedTextBoxNumber.TabIndex = 3;
//
// ButtonRefreshCollection
//
this.ButtonRefreshCollection.Location = new System.Drawing.Point(7, 160);
this.ButtonRefreshCollection.Name = "ButtonRefreshCollection";
this.ButtonRefreshCollection.Size = new System.Drawing.Size(187, 31);
this.ButtonRefreshCollection.TabIndex = 2;
this.ButtonRefreshCollection.Text = "Обновить коллекцию";
this.ButtonRefreshCollection.UseVisualStyleBackColor = true;
this.ButtonRefreshCollection.Click += new System.EventHandler(this.ButtonRefreshCollection_Click);
//
// ButtonRemoveArmoredCar
//
this.ButtonRemoveArmoredCar.Location = new System.Drawing.Point(7, 114);
this.ButtonRemoveArmoredCar.Name = "ButtonRemoveArmoredCar";
this.ButtonRemoveArmoredCar.Size = new System.Drawing.Size(187, 40);
this.ButtonRemoveArmoredCar.TabIndex = 1;
this.ButtonRemoveArmoredCar.Text = "Удалить бронированную машину";
this.ButtonRemoveArmoredCar.UseVisualStyleBackColor = true;
this.ButtonRemoveArmoredCar.Click += new System.EventHandler(this.ButtonRemoveArmoredCar_Click);
//
// ButtonAddArmoredCar
//
this.ButtonAddArmoredCar.Location = new System.Drawing.Point(7, 22);
this.ButtonAddArmoredCar.Name = "ButtonAddArmoredCar";
this.ButtonAddArmoredCar.Size = new System.Drawing.Size(187, 42);
this.ButtonAddArmoredCar.TabIndex = 0;
this.ButtonAddArmoredCar.Text = "Добавить бронированную машину";
this.ButtonAddArmoredCar.UseVisualStyleBackColor = true;
this.ButtonAddArmoredCar.Click += new System.EventHandler(this.ButtonAddArmoredCar_Click);
//
// pictureBoxCollection
//
this.pictureBoxCollection.Location = new System.Drawing.Point(1, 0);
this.pictureBoxCollection.Name = "pictureBoxCollection";
this.pictureBoxCollection.Size = new System.Drawing.Size(572, 438);
this.pictureBoxCollection.TabIndex = 1;
this.pictureBoxCollection.TabStop = false;
//
// FormArmoredCarCollection
//
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.pictureBoxCollection);
this.Controls.Add(this.groupBox1);
this.Name = "FormArmoredCarCollection";
this.Text = "Набор бронированных машин";
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).EndInit();
this.ResumeLayout(false);
}
#endregion
private GroupBox groupBox1;
private Button ButtonRefreshCollection;
private Button ButtonRemoveArmoredCar;
private Button ButtonAddArmoredCar;
private PictureBox pictureBoxCollection;
private MaskedTextBox maskedTextBoxNumber;
}
}

View File

@ -0,0 +1,68 @@
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 Tank.DrawingObjects;
using Tank.MovementStrategy;
using Tank.Generics;
namespace Tank
{
public partial class FormArmoredCarCollection : Form
{
private readonly TanksGenericCollection<DrawingArmoredCar,DrawingObjectArmoredCar> _tanks;
public FormArmoredCarCollection()
{
InitializeComponent();
_tanks = new TanksGenericCollection<DrawingArmoredCar, DrawingObjectArmoredCar>
(pictureBoxCollection.Width, pictureBoxCollection.Height);
}
private void ButtonAddArmoredCar_Click(object sender, EventArgs e)
{
FormTank form = new();
if (form.ShowDialog() == DialogResult.OK)
{
if (_tanks + form.SelectedTank != -1)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = _tanks.ShowTanks();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
}
private void ButtonRemoveArmoredCar_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
== DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (_tanks - pos != null)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = _tanks.ShowTanks();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
{
pictureBoxCollection.Image = _tanks.ShowTanks();
}
}
}

View File

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

View File

@ -34,6 +34,10 @@
this.buttonLeft = new System.Windows.Forms.Button();
this.buttonDown = new System.Windows.Forms.Button();
this.buttonRight = new System.Windows.Forms.Button();
this.buttonCreateArmoredCar = new System.Windows.Forms.Button();
this.buttonStep = new System.Windows.Forms.Button();
this.comboBoxStrategy = new System.Windows.Forms.ComboBox();
this.ButtonSelectTank = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxTank)).BeginInit();
this.SuspendLayout();
//
@ -52,9 +56,9 @@
//
this.buttonCreate.Location = new System.Drawing.Point(26, 417);
this.buttonCreate.Name = "buttonCreate";
this.buttonCreate.Size = new System.Drawing.Size(75, 23);
this.buttonCreate.Size = new System.Drawing.Size(97, 23);
this.buttonCreate.TabIndex = 1;
this.buttonCreate.Text = "Создать";
this.buttonCreate.Text = "Создать Танк";
this.buttonCreate.UseVisualStyleBackColor = true;
this.buttonCreate.Click += new System.EventHandler(this.buttonCreate_Click);
//
@ -62,7 +66,7 @@
//
this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonUp.BackgroundImage = global::Tank.Properties.Resources.upper_arrow;
this.buttonUp.Location = new System.Drawing.Point(806, 381);
this.buttonUp.Location = new System.Drawing.Point(772, 374);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(30, 30);
this.buttonUp.TabIndex = 2;
@ -73,7 +77,7 @@
//
this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonLeft.BackgroundImage = global::Tank.Properties.Resources.left_arrow;
this.buttonLeft.Location = new System.Drawing.Point(770, 417);
this.buttonLeft.Location = new System.Drawing.Point(736, 410);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(30, 30);
this.buttonLeft.TabIndex = 3;
@ -84,7 +88,7 @@
//
this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDown.BackgroundImage = global::Tank.Properties.Resources.down_arrow;
this.buttonDown.Location = new System.Drawing.Point(806, 417);
this.buttonDown.Location = new System.Drawing.Point(772, 410);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(30, 30);
this.buttonDown.TabIndex = 4;
@ -95,18 +99,63 @@
//
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::Tank.Properties.Resources.right_arrow;
this.buttonRight.Location = new System.Drawing.Point(842, 417);
this.buttonRight.Location = new System.Drawing.Point(808, 410);
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);
//
// buttonCreateArmoredCar
//
this.buttonCreateArmoredCar.Location = new System.Drawing.Point(129, 417);
this.buttonCreateArmoredCar.Name = "buttonCreateArmoredCar";
this.buttonCreateArmoredCar.Size = new System.Drawing.Size(210, 23);
this.buttonCreateArmoredCar.TabIndex = 7;
this.buttonCreateArmoredCar.Text = "Создать Бронированную машину\r\n";
this.buttonCreateArmoredCar.UseVisualStyleBackColor = true;
this.buttonCreateArmoredCar.Click += new System.EventHandler(this.buttonCreateArmoredCar_Click);
//
// buttonStep
//
this.buttonStep.Location = new System.Drawing.Point(753, 70);
this.buttonStep.Name = "buttonStep";
this.buttonStep.Size = new System.Drawing.Size(75, 23);
this.buttonStep.TabIndex = 9;
this.buttonStep.Text = "Шаг";
this.buttonStep.UseVisualStyleBackColor = true;
this.buttonStep.Click += new System.EventHandler(this.buttonStep_Click);
//
// comboBoxStrategy
//
this.comboBoxStrategy.FormattingEnabled = true;
this.comboBoxStrategy.Items.AddRange(new object[] {
"0",
"1"});
this.comboBoxStrategy.Location = new System.Drawing.Point(733, 41);
this.comboBoxStrategy.Name = "comboBoxStrategy";
this.comboBoxStrategy.Size = new System.Drawing.Size(121, 23);
this.comboBoxStrategy.TabIndex = 10;
//
// ButtonSelectTank
//
this.ButtonSelectTank.Location = new System.Drawing.Point(737, 113);
this.ButtonSelectTank.Name = "ButtonSelectTank";
this.ButtonSelectTank.Size = new System.Drawing.Size(117, 23);
this.ButtonSelectTank.TabIndex = 11;
this.ButtonSelectTank.Text = "Выбор машины";
this.ButtonSelectTank.UseVisualStyleBackColor = true;
this.ButtonSelectTank.Click += new System.EventHandler(this.ButtonSelectTank_Click);
//
// FormTank
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(884, 461);
this.Controls.Add(this.ButtonSelectTank);
this.Controls.Add(this.comboBoxStrategy);
this.Controls.Add(this.buttonStep);
this.Controls.Add(this.buttonCreateArmoredCar);
this.Controls.Add(this.buttonRight);
this.Controls.Add(this.buttonDown);
this.Controls.Add(this.buttonLeft);
@ -116,7 +165,7 @@
this.Name = "FormTank";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Tank";
this.Load += new System.EventHandler(this.Form1_Load);
this.Load += new System.EventHandler(this.FormTank_Load);
((System.ComponentModel.ISupportInitialize)(this.pictureBoxTank)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
@ -131,5 +180,9 @@
private Button buttonLeft;
private Button buttonDown;
private Button buttonRight;
private Button buttonCreateArmoredCar;
private Button buttonStep;
private ComboBox comboBoxStrategy;
private Button ButtonSelectTank;
}
}

View File

@ -1,3 +1,6 @@
using Tank.DrawingObjects;
using Tank.MovementStrategy;
namespace Tank
{
/// <summary>
@ -5,43 +8,32 @@ namespace Tank
/// </summary>
public partial class FormTank : Form
{
/// <summary>
/// Ïîëå-îáúåêò äëÿ ïðîðèñîâêè îáúåêòà
/// </summary>
private DrawningTank? _drawningTank;
/// <summary>
/// Èíèöèàëèçàöèÿ ôîðìû
/// </summary>
private DrawingArmoredCar? _Tank;
/// Ñòðàòåãèÿ ïåðåìåùåíèÿ
private AbstractStrategy? _abstractStrategy;
public DrawingArmoredCar? SelectedTank { get; private set; }
public FormTank()
{
InitializeComponent();
_abstractStrategy = null;
SelectedTank = null;
}
/// <summary>
/// Ìåòîä ïðîðèñîâêè ìàøèíû
/// </summary>
private void Draw()
{
if (_drawningTank == null)
if (_Tank == null)
{
return;
}
Bitmap bmp = new(pictureBoxTank.Width,
pictureBoxTank.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningTank.DrawTransport(gr);
_Tank.DrawTransport(gr);
pictureBoxTank.Image = bmp;
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_Load(object sender, EventArgs e)
{
}
private void pictureBox1_Click(object sender, EventArgs e)
{
@ -50,29 +42,42 @@ namespace Tank
private void buttonCreate_Click(object sender, EventArgs e)
{
Random random = new();
_drawningTank = new DrawningTank();
_drawningTank.Init(random.Next(100, 300),
random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256),
random.Next(0, 256)),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256),
random.Next(0, 256)),
Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)),
Color color = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
// âûáîð îñíîâíîãî öâåòà
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
Color dopColor = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
// âûáîð äîïîëíèòåëüíîãî öâåòà
ColorDialog dialog2 = new();
if (dialog2.ShowDialog() == DialogResult.OK)
{
dopColor = dialog2.Color;
}
_Tank = new DrawingTank(random.Next(100, 300),
random.Next(1000, 3000), color,
dopColor, Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)),
pictureBoxTank.Width, pictureBoxTank.Height);
_drawningTank.SetPosition(random.Next(10, 100),
_Tank.SetPosition(random.Next(10, 100),
random.Next(10, 100));
Draw();
}
/// <summary>
/// Èçìåíåíèå ðàçìåðîâ ôîðìû
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonMove_Click(object sender, EventArgs e)
{
if (_drawningTank == null)
if (_Tank == null)
{
return;
}
@ -80,20 +85,87 @@ namespace Tank
switch (name)
{
case "buttonUp":
_drawningTank.MoveTransport(Direction.Up);
_Tank.MoveTransport(Direction.Up);
break;
case "buttonDown":
_drawningTank.MoveTransport(Direction.Down);
_Tank.MoveTransport(Direction.Down);
break;
case "buttonLeft":
_drawningTank.MoveTransport(Direction.Left);
_Tank.MoveTransport(Direction.Left);
break;
case "buttonRight":
_drawningTank.MoveTransport(Direction.Right);
_Tank.MoveTransport(Direction.Right);
break;
}
Draw();
}
// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü Áðîíèðîâàííóþ ìàøèíó"
private void buttonCreateArmoredCar_Click(object sender, EventArgs e)
{
Random random = new();
Color color = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
_Tank = new DrawingArmoredCar(random.Next(100, 300), random.Next(1000, 3000), color,
pictureBoxTank.Width, pictureBoxTank.Height);
_Tank.SetPosition(random.Next(10, 100), random.Next(10,
100));
Draw();
}
private void buttonStep_Click(object sender, EventArgs e)
{
if (_Tank == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_abstractStrategy = comboBoxStrategy.SelectedIndex
switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(new
DrawingObjectArmoredCar(_Tank), pictureBoxTank.Width,
pictureBoxTank.Height);
}
if (_abstractStrategy == null)
{
return;
}
comboBoxStrategy.Enabled = false;
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_abstractStrategy = null;
}
}
private void FormTank_Load(object sender, EventArgs e)
{
}
private void ButtonSelectTank_Click(object sender, EventArgs e)
{
SelectedTank = _Tank;
DialogResult = DialogResult.OK;
}
}
}

View File

@ -0,0 +1,123 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tank.Generics
{
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T"></typeparam>
internal class SetGeneric<T> where T : class
{
/// <summary>
/// Массив объектов, которые храним
/// </summary>
private readonly T?[] _places;
/// <summary>
/// Количество объектов в массиве
/// </summary>
public int Count => _places.Length;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetGeneric(int count)
{
_places = new T?[count];
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="car">Добавляемый автомобиль</param>
/// <returns></returns>
public int Insert(T tank)
{
// вставка в начало набора
int index = -1;
for (int i = 0; i < _places.Length; i++)
{
if (_places[i] == null)
{
index = i;
break;
}
}
if (index < 0)
{
return -1;
}
for (int i = index; i > 0; i--)
{
_places[i] = _places[i - 1];
}
_places[0] = tank;
return 0;
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="car">Добавляемый автомобиль</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public int Insert(T tank, int position)
{
// проверка
if (position < 0 || position >= Count)
return -1;
if (_places[position] == null)
{
_places[position] = tank;
return position;
}
int index = -1;
for (int i = position; i < Count; i++)
{
if (_places[i] == null)
{
index = i; break;
}
}
if (index < 0)
return -1;
for (int i = index; index > position; i--)
{
_places[i] = _places[i - 1];
}
_places[position] = tank;
return position;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public bool Remove(int position)
{
// проверка позиции
if (position < 0 || position >= Count)
{
return false;
}
_places[position] = null;
return true;
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T? Get(int position)
{
// проверка позиции
if (position < 0 || position >= Count)
{
return null;
}
return _places[position];
}
}
}

View File

@ -0,0 +1,144 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tank.MovementStrategy;
using Tank.DrawingObjects;
using Tank.MovementStrategy;
namespace Tank.Generics
{
/// <summary>
/// Параметризованный класс для набора объектов DrawningCar
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
internal class TanksGenericCollection<T, U>
where T : DrawingArmoredCar
where U : IMoveableObject
{
/// <summary>
/// Ширина окна прорисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна прорисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Размер занимаемого объектом места (ширина)
/// </summary>
private readonly int _placeSizeWidth = 160;
/// <summary>
/// Размер занимаемого объектом места (высота)
/// </summary>
private readonly int _placeSizeHeight = 65;
/// <summary>
/// Набор объектов
/// </summary>
private readonly SetGeneric<T> _collection;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
public TanksGenericCollection(int picWidth, int picHeight)
{
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = new SetGeneric<T>(width * height);
}
/// <summary>
/// Перегрузка оператора сложения
/// </summary>
/// <param name="collect"></param>
/// <param name="obj"></param>
/// <returns></returns>
public static int operator +(TanksGenericCollection<T, U> collect, T?
obj)
{
if (obj == null)
{
return -1;
}
return collect._collection.Insert(obj);
}
/// <summary>
/// Перегрузка оператора вычитания
/// </summary>
/// <param name="collect"></param>
/// <param name="pos"></param>
/// <returns></returns>
public static bool operator -(TanksGenericCollection<T, U> collect, int
pos)
{
T? obj = collect._collection.Get(pos);
if (obj != null)
{
return collect._collection.Remove(pos);
}
return false;
}
/// <summary>
/// Получение объекта IMoveableObject
/// </summary>
/// <param name="pos"></param>
/// <returns></returns>
public U? GetU(int pos)
{
return (U?)_collection.Get(pos)?.GetMoveableObject;
}
/// <summary>
/// Вывод всего набора объектов
/// </summary>
/// <returns></returns>
public Bitmap ShowTanks()
{
Bitmap bmp = new(_pictureWidth, _pictureHeight);
Graphics gr = Graphics.FromImage(bmp);
DrawBackground(gr);
DrawObjects(gr);
return bmp;
}
/// <summary>
/// Метод отрисовки фона
/// </summary>
/// <param name="g"></param>
private void DrawBackground(Graphics g)
{
Pen pen = new(Color.Black, 3);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j)
{ //разметка
g.DrawLine(pen, i * _placeSizeWidth, j *
_placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth / 2 + 40, j * _placeSizeHeight);
}
g.DrawLine(pen, i * _placeSizeWidth, 0, i *
_placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight);
}
}
/// <summary>
/// Метод прорисовки объектов
/// </summary>
/// <param name="g"></param>
private void DrawObjects(Graphics g)
{
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
for (int i = 0; i < _collection.Count; i++)
{
DrawingArmoredCar? tank = _collection.Get(i);
if (tank != null)
{
tank.SetPosition(i % width * _placeSizeWidth, (i / (_pictureWidth / _placeSizeWidth)) * _placeSizeHeight);
tank.DrawTransport(g);
}
}
}
}
}

View File

@ -0,0 +1,73 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tank.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;
FieldHeight = height;
FieldWidth = width;
}
public void MakeStep()
{
if (_state != Status.InProgress)
return;
if (IsTargetDestination())
{
_state = Status.Finish;
return;
}
MoveToTarget();
}
protected bool MoveLeft() => MoveTo(Direction.Left);
protected bool MoveRight() => MoveTo(Direction.Right);
protected bool MoveUp() => MoveTo(Direction.Up);
protected bool MoveDown() => MoveTo(Direction.Down);
protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectParameters;
protected int? GetStep()
{
if (_state != Status.InProgress)
{
return null;
}
return _moveableObject?.GetStep;
}
protected abstract void MoveToTarget();
protected abstract bool IsTargetDestination();
private bool MoveTo(Direction direction)
{
if (_state != Status.InProgress)
return false;
if (_moveableObject?.CheckCanMove(direction) ?? false)
{
_moveableObject.MoveObject(direction);
return true;
}
return false;
}
}
}

View File

@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tank.DrawingObjects;
namespace Tank.MovementStrategy
{
/// Реализация интерфейса IDrawningObject для работы с объектом DrawningCar (паттерн Adapter)
public class DrawingObjectArmoredCar : IMoveableObject
{
private readonly DrawingArmoredCar? _drawingArmoredCar = null;
public DrawingObjectArmoredCar(DrawingArmoredCar drawingArmoredCar)
{
_drawingArmoredCar = drawingArmoredCar;
}
public ObjectParameters? GetObjectParameters
{
get
{
if (_drawingArmoredCar == null || _drawingArmoredCar.Tank ==
null)
{
return null;
}
return new ObjectParameters(_drawingArmoredCar.GetPosX,
_drawingArmoredCar.GetPosY, _drawingArmoredCar.GetWidth, _drawingArmoredCar.GetHeight);
}
}
public int GetStep => (int)(_drawingArmoredCar?.Tank?.Step ?? 0);
public bool CheckCanMove(Direction direction) =>
_drawingArmoredCar?.CanMove(direction) ?? false;
public void MoveObject(Direction direction) =>
_drawingArmoredCar?.MoveTransport(direction);
}
}

View File

@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tank.DrawingObjects;
namespace Tank.MovementStrategy
{
/// <summary>
/// Интерфейс для работы с перемещаемым объектом
/// </summary>
public interface IMoveableObject
{
/// <summary>
/// Получение координаты X объекта
/// </summary>
ObjectParameters? GetObjectParameters { get; }
/// <summary>
/// Шаг объекта
/// </summary>
int GetStep { get; }
/// <summary>
/// Проверка, можно ли переместиться по нужному направлению
/// </summary>
/// <param name="direction"></param>
/// <returns></returns>
bool CheckCanMove(Direction direction);
/// <summary>
/// Изменение направления пермещения объекта
/// </summary>
/// <param name="direction">Направление</param>
void MoveObject(Direction direction);
}
}

View File

@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tank.MovementStrategy
{
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestination()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.RightBorder + GetStep() >= FieldWidth &&
objParams.DownBorder + GetStep() >= FieldHeight &&
objParams.RightBorder <= FieldWidth &&
objParams.DownBorder <= 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,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tank.MovementStrategy
{
public class MoveToCenter : AbstractStrategy
{
protected override bool IsTargetDestination()
{
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,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tank.MovementStrategy
{
/// <summary>
/// Параметры-координаты объекта
/// </summary>
public class ObjectParameters
{
private readonly int _x;
private readonly int _y;
private readonly int _width;
private readonly int _height;
/// <summary>
/// Левая граница
/// </summary>
public int LeftBorder => _x;
/// <summary>
/// Верхняя граница
/// </summary>
public int TopBorder => _y;
/// <summary>
/// Правая граница
/// </summary>
public int RightBorder => _x + _width;
/// <summary>
/// Нижняя граница
/// </summary>
public int DownBorder => _y + _height;
/// <summary>
/// Середина объекта
/// </summary>
public int ObjectMiddleHorizontal => _x + _width / 2;
/// <summary>
/// Середина объекта
/// </summary>
public int ObjectMiddleVertical => _y + _height / 2;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
public ObjectParameters(int x, int y, int width, int height)
{
_x = x;
_y = y;
_width = width;
_height = height;
}
}
}

View File

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

View File

@ -11,7 +11,7 @@ namespace Tank
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormTank());
Application.Run(new FormArmoredCarCollection());
}
}
}

View File

@ -23,4 +23,9 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<Folder Include="Drawings\" />
<Folder Include="MovementStrategy\" />
</ItemGroup>
</Project>