Compare commits

...

5 Commits

Author SHA1 Message Date
5419c0c52d laba3 is done 2023-11-14 22:20:19 +04:00
ce904c5005 code dubbed 2023-11-14 22:20:19 +04:00
66f19085b9 Edited from first lab 2023-11-14 22:20:19 +04:00
7e28d26868 lab2 is done with amendment 2023-11-14 22:20:19 +04:00
de4231767b lab2 is done 2023-11-14 22:20:19 +04:00
20 changed files with 1442 additions and 243 deletions

View File

@ -0,0 +1,134 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectTank.DrawningObjects;
namespace ProjectTank.MovementStrategy
{
/// <summary>
/// Класс-стратегия перемещения объекта
/// </summary>
public abstract class AbstractStrategy
{
/// <summary>
/// Перемещаемый объект
/// </summary>
private IMoveableObject? _moveableObject;
/// <summary>
/// Статус перемещения
/// </summary>
private Status _state = Status.NotInit;
/// <summary>
/// Ширина поля
/// </summary>
protected int FieldWidth { get; private set; }
/// <summary>
/// Высота поля
/// </summary>
protected int FieldHeight { get; private set; }
/// <summary>
/// Статус перемещения
/// </summary>
public Status GetStatus() { return _state; }
/// <summary>
/// Установка данных
/// </summary>
/// <param name="moveableObject">Перемещаемый объект</param>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
public void SetData(IMoveableObject moveableObject, int width, int
height)
{
if (moveableObject == null)
{
_state = Status.NotInit;
return;
}
_state = Status.InProgress;
_moveableObject = moveableObject;
FieldWidth = width;
FieldHeight = height;
}
/// <summary>
/// Шаг перемещения
/// </summary>
public void MakeStep()
{
if (_state != Status.InProgress)
{
return;
}
if (IsTargetDestinaion())
{
_state = Status.Finish;
return;
}
MoveToTarget();
}
/// <summary>
/// Перемещение влево
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false -неудача)</returns>
protected bool MoveLeft() => MoveTo(DirectionType.Left);
/// <summary>
/// Перемещение вправо
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться,false - неудача)</returns>
protected bool MoveRight() => MoveTo(DirectionType.Right);
/// <summary>
/// Перемещение вверх
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться,false - неудача)</returns>
protected bool MoveUp() => MoveTo(DirectionType.Up);
/// <summary>
/// Перемещение вниз
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться,false - неудача)</returns>
protected bool MoveDown() => MoveTo(DirectionType.Down);
/// <summary>
/// Параметры объекта
/// </summary>
protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectPosition;
/// <summary>
/// Шаг объекта
/// </summary>
/// <returns></returns>
protected int? GetStep()
{
if (_state != Status.InProgress)
{
return null;
}
return _moveableObject?.GetStep;
}
/// <summary>
/// Перемещение к цели
/// </summary>
protected abstract void MoveToTarget();
/// <summary>
/// Достигнута ли цель
/// </summary>
/// <returns></returns>
protected abstract bool IsTargetDestinaion();
/// <summary>
/// Попытка перемещения в требуемом направлении
/// </summary>
/// <param name="directionType">Направление</param>
/// <returns>Результат попытки (true - удалось переместиться, false - неудача)</returns>
private bool MoveTo(DirectionType directionType)
{
if (_state != Status.InProgress)
{
return false;
}
if (_moveableObject?.CheckCanMove(directionType) ?? false)
{
_moveableObject.MoveObject(directionType);
return true;
}
return false;
}
}
}

View File

@ -0,0 +1,142 @@
namespace ProjectTank
{
partial class ArmoredTransportCollectionForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.ArmoredTransportCollectionFormToolsGroup = new System.Windows.Forms.GroupBox();
this.ButtonRefreshCollection = new System.Windows.Forms.Button();
this.ButtonRemoveArmoredTransport = new System.Windows.Forms.Button();
this.maskedTextBoxNumber = new System.Windows.Forms.TextBox();
this.ButtonAddArmoredTransport = new System.Windows.Forms.Button();
this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
this.pictureBoxCollection = new System.Windows.Forms.PictureBox();
this.ArmoredTransportCollectionFormToolsGroup.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).BeginInit();
this.SuspendLayout();
//
// ArmoredTransportCollectionFormToolsGroup
//
this.ArmoredTransportCollectionFormToolsGroup.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Right)));
this.ArmoredTransportCollectionFormToolsGroup.Controls.Add(this.ButtonRefreshCollection);
this.ArmoredTransportCollectionFormToolsGroup.Controls.Add(this.ButtonRemoveArmoredTransport);
this.ArmoredTransportCollectionFormToolsGroup.Controls.Add(this.maskedTextBoxNumber);
this.ArmoredTransportCollectionFormToolsGroup.Controls.Add(this.ButtonAddArmoredTransport);
this.ArmoredTransportCollectionFormToolsGroup.Location = new System.Drawing.Point(1057, -4);
this.ArmoredTransportCollectionFormToolsGroup.Name = "ArmoredTransportCollectionFormToolsGroup";
this.ArmoredTransportCollectionFormToolsGroup.Size = new System.Drawing.Size(431, 865);
this.ArmoredTransportCollectionFormToolsGroup.TabIndex = 0;
this.ArmoredTransportCollectionFormToolsGroup.TabStop = false;
this.ArmoredTransportCollectionFormToolsGroup.Text = "Инструменты";
//
// ButtonRefreshCollection
//
this.ButtonRefreshCollection.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.ButtonRefreshCollection.Location = new System.Drawing.Point(22, 394);
this.ButtonRefreshCollection.Name = "ButtonRefreshCollection";
this.ButtonRefreshCollection.Size = new System.Drawing.Size(391, 47);
this.ButtonRefreshCollection.TabIndex = 3;
this.ButtonRefreshCollection.Text = "Обновить коллекцию";
this.ButtonRefreshCollection.UseVisualStyleBackColor = true;
this.ButtonRefreshCollection.Click += new System.EventHandler(this.ButtonRefreshCollection_Click);
//
// ButtonRemoveArmoredTransport
//
this.ButtonRemoveArmoredTransport.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.ButtonRemoveArmoredTransport.Location = new System.Drawing.Point(22, 251);
this.ButtonRemoveArmoredTransport.Name = "ButtonRemoveArmoredTransport";
this.ButtonRemoveArmoredTransport.Size = new System.Drawing.Size(391, 82);
this.ButtonRemoveArmoredTransport.TabIndex = 2;
this.ButtonRemoveArmoredTransport.Text = "Удалить бронированный транспорт";
this.ButtonRemoveArmoredTransport.UseVisualStyleBackColor = true;
this.ButtonRemoveArmoredTransport.Click += new System.EventHandler(this.ButtonRemoveArmoredTransport_Click);
//
// maskedTextBoxNumber
//
this.maskedTextBoxNumber.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.maskedTextBoxNumber.Location = new System.Drawing.Point(71, 188);
this.maskedTextBoxNumber.Name = "maskedTextBoxNumber";
this.maskedTextBoxNumber.Size = new System.Drawing.Size(275, 39);
this.maskedTextBoxNumber.TabIndex = 1;
//
// ButtonAddArmoredTransport
//
this.ButtonAddArmoredTransport.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.ButtonAddArmoredTransport.Location = new System.Drawing.Point(22, 88);
this.ButtonAddArmoredTransport.Name = "ButtonAddArmoredTransport";
this.ButtonAddArmoredTransport.Size = new System.Drawing.Size(391, 82);
this.ButtonAddArmoredTransport.TabIndex = 0;
this.ButtonAddArmoredTransport.Text = "Добавить бронированный транспорт";
this.ButtonAddArmoredTransport.UseVisualStyleBackColor = true;
this.ButtonAddArmoredTransport.Click += new System.EventHandler(this.ButtonAddArmoredTransport_Click);
//
// contextMenuStrip1
//
this.contextMenuStrip1.ImageScalingSize = new System.Drawing.Size(32, 32);
this.contextMenuStrip1.Name = "contextMenuStrip1";
this.contextMenuStrip1.Size = new System.Drawing.Size(61, 4);
//
// pictureBoxCollection
//
this.pictureBoxCollection.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBoxCollection.Location = new System.Drawing.Point(0, 0);
this.pictureBoxCollection.Name = "pictureBoxCollection";
this.pictureBoxCollection.Size = new System.Drawing.Size(1492, 873);
this.pictureBoxCollection.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pictureBoxCollection.TabIndex = 2;
this.pictureBoxCollection.TabStop = false;
//
// ArmoredTransportCollectionForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(13F, 32F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1492, 873);
this.Controls.Add(this.ArmoredTransportCollectionFormToolsGroup);
this.Controls.Add(this.pictureBoxCollection);
this.Name = "ArmoredTransportCollectionForm";
this.Text = "ArmoredTransportCollectionForm";
this.ArmoredTransportCollectionFormToolsGroup.ResumeLayout(false);
this.ArmoredTransportCollectionFormToolsGroup.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private GroupBox ArmoredTransportCollectionFormToolsGroup;
private Button ButtonRefreshCollection;
private Button ButtonRemoveArmoredTransport;
private TextBox maskedTextBoxNumber;
private Button ButtonAddArmoredTransport;
private ContextMenuStrip contextMenuStrip1;
private PictureBox pictureBoxCollection;
}
}

View File

@ -0,0 +1,88 @@
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 ProjectTank.DrawningObjects;
using ProjectTank.Generics;
using ProjectTank.MovementStrategy;
namespace ProjectTank
{
/// <summary>
/// Форма для работы с набором объектов класса DrawningCar
/// </summary>
public partial class ArmoredTransportCollectionForm : Form
{
/// <summary>
/// Набор объектов
/// </summary>
private readonly ArmoredTransportsGenericCollection<DrawningArmoredTransport, DrawningObjectArmoredTransport> _armoredTransports;
/// <summary>
/// Конструктор
/// </summary>
public ArmoredTransportCollectionForm()
{
InitializeComponent();
_armoredTransports = new ArmoredTransportsGenericCollection<DrawningArmoredTransport,DrawningObjectArmoredTransport>(pictureBoxCollection.Width, pictureBoxCollection.Height);
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddArmoredTransport_Click(object sender, EventArgs e)
{
TankForm form = new();
if (form.ShowDialog() == DialogResult.OK)
{
if (_armoredTransports + form.SelectedArmoredTransport != null)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = _armoredTransports.ShowArmoredTransports();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
}
/// <summary>
/// Удаление объекта из набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveArmoredTransport_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (_armoredTransports - pos != null)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = _armoredTransports.ShowArmoredTransports();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
/// <summary>
/// Обновление рисунка по набору
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRefreshCollection_Click(object sender, EventArgs
e)
{
pictureBoxCollection.Image = _armoredTransports.ShowArmoredTransports();
}
}
}

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="contextMenuStrip1.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,150 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectTank.DrawningObjects;
using ProjectTank.MovementStrategy;
namespace ProjectTank.Generics
{
/// <summary>
/// Параметризованный класс для набора объектов DrawningArmoredTransport
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
internal class ArmoredTransportsGenericCollection<T, U>
where T : DrawningArmoredTransport
where U : IMoveableObject
{
/// <summary>
/// Коэффициент изменения ширины парковки
/// </summary>
readonly int koefWidth = 2;
/// <summary>
/// Ширина окна прорисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна прорисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Размер занимаемого объектом места (ширина)
/// </summary>
private readonly int _placeSizeWidth = 200;
/// <summary>
/// Размер занимаемого объектом места (высота)
/// </summary>
private readonly int _placeSizeHeight = 90;
/// <summary>
/// Набор объектов
/// </summary>
private readonly SetGeneric<T> _collection;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
public ArmoredTransportsGenericCollection(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 +(ArmoredTransportsGenericCollection<T, U> collect, T? obj)
{
if (obj == null || collect == null)
{
return -1;
}
return collect._collection.Insert(obj);
}
/// <summary>
/// Перегрузка оператора вычитания
/// </summary>
/// <param name="collect"></param>
/// <param name="pos"></param>
/// <returns></returns>
public static bool operator -(ArmoredTransportsGenericCollection<T, U> collect, int pos)
{
T? obj = collect?._collection.Get(pos);
if (obj != null && collect != 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 ShowArmoredTransports()
{
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)/koefWidth; i++) //изменение ширины парковки
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j)
{
//линия рамзетки места
g.DrawLine(pen, i * _placeSizeWidth, j * _placeSizeHeight,
i * _placeSizeWidth + _placeSizeWidth / 2, j *_placeSizeHeight);
g.DrawString("P", new Font("Courier New", 30.0F), new SolidBrush(Color.Blue),
new Point(i * _placeSizeWidth, (j-1) * _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)/koefWidth; //изменение ширины парковки
int height = _pictureHeight / _placeSizeHeight;
for (int i = 0; i < _collection.Count; i++)
{
DrawningArmoredTransport? armoredTransport = _collection.Get(i);
if (armoredTransport != null)
{
int row = height - 1 - (i / width);
int col = width - 1 - (i % width);
armoredTransport.SetPosition(col * _placeSizeWidth, row * _placeSizeHeight);
armoredTransport.DrawTransport(g);
}
}
}
}
}

View File

@ -1,28 +1,28 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace ProjectTank namespace ProjectTank
{ {
public enum DirectionType public enum DirectionType
{ {
/// <summary> /// <summary>
/// Вверх /// Вверх
/// </summary> /// </summary>
Up = 1, Up = 1,
/// <summary> /// <summary>
/// Вниз /// Вниз
/// </summary> /// </summary>
Down = 2, Down = 2,
/// <summary> /// <summary>
/// Влево /// Влево
/// </summary> /// </summary>
Left = 3, Left = 3,
/// <summary> /// <summary>
/// Вправо /// Вправо
/// </summary> /// </summary>
Right = 4 Right = 4
} }
} }

View File

@ -0,0 +1,228 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectTank.Entities;
using ProjectTank.MovementStrategy;
namespace ProjectTank.DrawningObjects
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningArmoredTransport
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityArmoredTransport? EntityArmoredTransport { get; protected set; }
/// <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 _transportWidth = 200;
/// <summary>
/// Высота прорисовки транспорта
/// </summary>
protected readonly int _transportHeight = 80;
/// <summary>
/// Координата X объекта
/// </summary>
public int GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _transportWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _transportHeight;
/// <summary>
/// Получение объекта IMoveableObject из объекта DrawningArmoredTransport
/// </summary>
public IMoveableObject GetMoveableObject => new DrawningObjectArmoredTransport(this);
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public DrawningArmoredTransport(int speed, double weight, Color bodyColor, int
width, int height)
{
if ((height > _transportHeight) && (width > _transportWidth))
{
EntityArmoredTransport = new EntityArmoredTransport(speed, weight, bodyColor);
}
_pictureWidth = width;
_pictureHeight = height;
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <param name="transportWidth">Ширина прорисовки транспорта</param>
/// <param name="transportHeight">Высота прорисовки транспорта</param>
protected DrawningArmoredTransport(int speed, double weight, Color bodyColor, int
width, int height, int transportWidth, int transportHeight)
{
if ((height > transportHeight) && (width > transportWidth))
{
EntityArmoredTransport = new EntityArmoredTransport(speed, weight, bodyColor);
}
_pictureWidth = width;
_pictureHeight = height;
_transportWidth = transportWidth;
_transportHeight = transportHeight;
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
if ((x < 0 || y < 0) || (x + _transportWidth > _pictureWidth || y + _transportHeight > _pictureHeight))
{
_startPosX = 0;
_startPosY = 0;
}
else
{
_startPosX = x;
_startPosY = y;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public virtual void DrawTransport(Graphics g)
{
if (EntityArmoredTransport == null)
{
return;
}
Pen pen = new(Color.Black, 3);
Pen penGray = new(Color.Gray, 4);
Brush grayColorBrush = new SolidBrush(Color.Gray);
Brush blackColorBrush = new SolidBrush(Color.Black);
Brush bodyBrush = new SolidBrush(EntityArmoredTransport.BodyColor);
// Границы транспорта
// гусеницы
g.DrawEllipse(pen, _startPosX + 14, _startPosY + 44, 151, 31);
g.FillEllipse(blackColorBrush, _startPosX + 15, _startPosY + 45, 150, 30);
g.DrawEllipse(penGray, _startPosX + 24, _startPosY + 54, 10, 10);
g.DrawEllipse(penGray, _startPosX + 144, _startPosY + 54, 10, 10);
g.DrawEllipse(penGray, _startPosX + 44, _startPosY + 59, 10, 10);
g.DrawEllipse(penGray, _startPosX + 124, _startPosY + 59, 10, 10);
g.DrawEllipse(penGray, _startPosX + 64, _startPosY + 61, 10, 10);
g.DrawEllipse(penGray, _startPosX + 104, _startPosY + 61, 10, 10);
g.DrawEllipse(penGray, _startPosX + 84, _startPosY + 62, 10, 10);
// Кузов
g.DrawRectangle(pen, _startPosX + 19, _startPosY + 34, 141, 21);
g.FillRectangle(bodyBrush, _startPosX + 20, _startPosY + 35, 140, 20);
// Башня
g.FillRectangle(blackColorBrush, _startPosX + 75, _startPosY + 10, 25, 5);
g.DrawRectangle(pen, _startPosX + 64, _startPosY + 14, 66, 21);
g.FillRectangle(bodyBrush, _startPosX + 65, _startPosY + 15, 65, 20);
//Точки для отрисовки передней и задней части
Point pointFirstBackSide = new Point(_startPosX + 18, _startPosY + 35);
Point pointSecondBackSide = new Point(_startPosX + 18, _startPosY + 55);
Point pointThirdBackSide = new Point(_startPosX + 0, _startPosY + 55);
Point pointFirstFrontSide = new Point(_startPosX + 162, _startPosY + 35);
Point pointSecondFrontSide = new Point(_startPosX + 185, _startPosY + 55);
Point pointThirdFrontSide = new Point(_startPosX + 162, _startPosY + 55);
// Задняя часть
Point[] backSide = { pointFirstBackSide, pointSecondBackSide, pointThirdBackSide };
g.DrawPolygon(pen, backSide);
g.FillPolygon(bodyBrush, backSide);
// Передняя часть
Point[] frontSide = { pointFirstFrontSide, pointSecondFrontSide, pointThirdFrontSide };
g.DrawPolygon(pen, frontSide);
g.FillPolygon(bodyBrush, frontSide);
}
/// <summary>
/// Проверка, что объект может переместится по указанному направлению
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - можно переместится по указанномунаправлению</returns>
public bool CanMove(DirectionType direction)
{
if (EntityArmoredTransport == null)
{
return false;
}
return direction switch
{
//влево
DirectionType.Left => _startPosX - EntityArmoredTransport.Step > 0,
//вверх
DirectionType.Up => _startPosY - EntityArmoredTransport.Step > 0,
// вправо
DirectionType.Right => _startPosX + _transportWidth + EntityArmoredTransport.Step < _pictureWidth,
//вниз
DirectionType.Down => _startPosY + _transportHeight + EntityArmoredTransport.Step < _pictureHeight,
_ => false,
};
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
public void MoveTransport(DirectionType direction)
{
if (!CanMove(direction) || EntityArmoredTransport == null)
{
return;
}
switch (direction)
{
//влево
case DirectionType.Left:
_startPosX -= (int)EntityArmoredTransport.Step;
break;
//вверх
case DirectionType.Up:
_startPosY -= (int)EntityArmoredTransport.Step;
break;
// вправо
case DirectionType.Right:
_startPosX += (int)EntityArmoredTransport.Step;
break;
//вниз
case DirectionType.Down:
_startPosY += (int)EntityArmoredTransport.Step;
break;
}
}
}
}

View File

@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectTank.DrawningObjects;
namespace ProjectTank.MovementStrategy
{
/// <summary>
/// Реализация интерфейса IDrawningObject для работы с объектом DrawningCar(паттерн Adapter)
/// </summary>
public class DrawningObjectArmoredTransport : IMoveableObject
{
private readonly DrawningArmoredTransport? _drawningArmoredTransport = null;
public DrawningObjectArmoredTransport(DrawningArmoredTransport drawningArmoredTransport)
{
_drawningArmoredTransport = drawningArmoredTransport;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_drawningArmoredTransport == null || _drawningArmoredTransport.EntityArmoredTransport == null)
{
return null;
}
return new ObjectParameters(_drawningArmoredTransport.GetPosX, _drawningArmoredTransport.GetPosY,
_drawningArmoredTransport.GetWidth, _drawningArmoredTransport.GetHeight);
}
}
public int GetStep => (int)(_drawningArmoredTransport?.EntityArmoredTransport?.Step ?? 0);
public bool CheckCanMove(DirectionType direction) =>_drawningArmoredTransport?.CanMove(direction) ?? false;
public void MoveObject(DirectionType direction) =>_drawningArmoredTransport?.MoveTransport(direction);
}
}

View File

@ -1,182 +1,50 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Drawing;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using ProjectTank.Entities;
namespace ProjectTank namespace ProjectTank.DrawningObjects
{ {
public class DrawningTank /// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawningTank : DrawningArmoredTransport
{ {
/// <summary> /// <summary>
/// Класс-сущность /// Конструктор
/// </summary>
public EntityTank? _EntityTank { get; private set; }
/// <summary>
/// Ширина окна
/// </summary>
private int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int _pictureHeight;
/// <summary>
/// Левая координата прорисовки танка
/// </summary>
private int _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки танка
/// </summary>
private int _startPosY;
/// <summary>
/// Ширина прорисовки танка
/// </summary>
private readonly int _tankWidth = 200;
/// <summary>
/// Высота прорисовки танка
/// </summary>
private readonly int _tankHeight = 80;
/// <summary>
/// Инициализация свойств
/// </summary> /// </summary>
/// <param name="speed">Скорость</param> /// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param> /// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет кузова</param> /// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param> /// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="gun">Пушка</param>
/// <param name="machineGun">Пулемет</param>
/// <param name="width">Ширина картинки</param> /// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param> /// <param name="height">Высота картинки</param>
/// <returns>true - объект создан, false - проверка не пройдена,нельзя создать объект в этих размерах</returns> public DrawningTank(int speed, double weight, Color bodyColor, Color
public bool Init(int speed, double weight, Color bodyColor, Color additionalColor, additionalColor, bool gun, bool machineGun, int width, int height) : base(speed,weight, bodyColor, width, height, 200, 80)
bool gun, bool machineGun, int width, int height)
{ {
_pictureWidth = width; if (EntityArmoredTransport != null)
_pictureHeight = height;
if ((_pictureHeight < _tankHeight) || (_pictureWidth < _tankWidth))
{ {
return false; EntityArmoredTransport = new EntityTank(speed, weight, bodyColor,
} additionalColor, gun, machineGun);
_EntityTank = new EntityTank();
_EntityTank.Init(speed, weight, gun, machineGun, bodyColor, additionalColor);
return true;
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
if ((x < 0 || y < 0) || (x + _tankWidth > _pictureWidth || y + _tankHeight > _pictureHeight))
{
_startPosX = 0;
_startPosY = 0;
}
else
{
_startPosX = x;
_startPosY = y;
} }
} }
/// <summary> public override void DrawTransport(Graphics g)
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
public void MoveTransport(DirectionType direction)
{ {
if (_EntityTank == null) if (EntityArmoredTransport is not EntityTank tank)
{
return;
}
switch (direction)
{
//влево
case DirectionType.Left:
if (_startPosX - _EntityTank.Step > 0)
{
_startPosX -= (int)_EntityTank.Step;
}
break;
//вверх
case DirectionType.Up:
if (_startPosY - _EntityTank.Step > 0)
{
_startPosY -= (int)_EntityTank.Step;
}
break;
//вправо
case DirectionType.Right:
if (_startPosX + _tankWidth + _EntityTank.Step < _pictureWidth)
{
_startPosX += (int)_EntityTank.Step;
}
break;
//вниз
case DirectionType.Down:
if (_startPosY + _tankHeight + _EntityTank.Step < _pictureHeight)
{
_startPosY += (int)_EntityTank.Step;
}
break;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
{
if (_EntityTank == null)
{ {
return; return;
} }
Pen pen = new(Color.Black, 3); Pen pen = new(Color.Black, 3);
Pen penGray = new(Color.Gray, 4);
Brush grayColorBrush = new SolidBrush(Color.Gray);
Brush blackColorBrush = new SolidBrush(Color.Black); Brush blackColorBrush = new SolidBrush(Color.Black);
Brush additionalBrush = new SolidBrush(_EntityTank.AdditionalColor); Brush additionalBrush = new SolidBrush(tank.AdditionalColor);
Brush bodyBrush = new SolidBrush(_EntityTank.BodyColor);
// Границы автомобиля
// гусеницы
g.DrawEllipse(pen, _startPosX+14, _startPosY+44, 151, 31);
g.FillEllipse(blackColorBrush, _startPosX + 15, _startPosY + 45, 150, 30);
g.DrawEllipse(penGray, _startPosX + 24, _startPosY + 54, 10, 10);
g.DrawEllipse(penGray, _startPosX + 144, _startPosY + 54, 10, 10);
g.DrawEllipse(penGray, _startPosX + 44, _startPosY + 59, 10, 10);
g.DrawEllipse(penGray, _startPosX + 124, _startPosY + 59, 10, 10);
g.DrawEllipse(penGray, _startPosX + 64, _startPosY + 61, 10, 10);
g.DrawEllipse(penGray, _startPosX + 104, _startPosY + 61, 10, 10);
g.DrawEllipse(penGray, _startPosX + 84, _startPosY + 62, 10, 10);
// Кузов
g.DrawRectangle(pen, _startPosX + 19, _startPosY + 34, 141, 21);
g.FillRectangle(bodyBrush, _startPosX+20, _startPosY+35, 140, 20);
// Башня
g.FillRectangle(blackColorBrush, _startPosX + 75, _startPosY + 10, 25, 5);
g.DrawRectangle(pen, _startPosX + 64, _startPosY + 14, 66, 21);
g.FillRectangle(additionalBrush, _startPosX + 65, _startPosY + 15, 65, 20);
//Точки для отрисовки передней и задней части
Point pointFirstBackSide = new Point(_startPosX + 18, _startPosY + 35);
Point pointSecondBackSide = new Point(_startPosX + 18, _startPosY + 55);
Point pointThirdBackSide = new Point(_startPosX+0, _startPosY+55);
Point pointFirstFrontSide = new Point(_startPosX + 162, _startPosY + 35);
Point pointSecondFrontSide = new Point(_startPosX + 185, _startPosY + 55);
Point pointThirdFrontSide = new Point(_startPosX + 162, _startPosY + 55);
// Задняя часть
Point[] backSide = { pointFirstBackSide, pointSecondBackSide, pointThirdBackSide };
g.DrawPolygon(pen, backSide);
g.FillPolygon(bodyBrush, backSide);
// Передняя часть
Point[] frontSide ={ pointFirstFrontSide, pointSecondFrontSide, pointThirdFrontSide };
g.DrawPolygon(pen, frontSide);
g.FillPolygon(bodyBrush, frontSide);
// пушка // пушка
if (_EntityTank.Gun) if (tank.Gun)
{ {
g.DrawRectangle(pen, _startPosX + 129, _startPosY + 19, 56, 6); g.DrawRectangle(pen, _startPosX + 129, _startPosY + 19, 56, 6);
g.FillRectangle(additionalBrush, _startPosX + 130, _startPosY + 20, 55, 5); g.FillRectangle(additionalBrush, _startPosX + 130, _startPosY + 20, 55, 5);
@ -184,7 +52,7 @@ namespace ProjectTank
g.FillRectangle(blackColorBrush, _startPosX + 185, _startPosY + 18, 15, 10); g.FillRectangle(blackColorBrush, _startPosX + 185, _startPosY + 18, 15, 10);
} }
// пулемет // пулемет
if (_EntityTank.MachineGun) if (tank.MachineGun)
{ {
g.DrawRectangle(pen, _startPosX + 104, _startPosY + 9, 16, 6); g.DrawRectangle(pen, _startPosX + 104, _startPosY + 9, 16, 6);
g.FillRectangle(additionalBrush, _startPosX + 105, _startPosY + 10, 15, 5); g.FillRectangle(additionalBrush, _startPosX + 105, _startPosY + 10, 15, 5);
@ -195,6 +63,7 @@ namespace ProjectTank
g.FillRectangle(additionalBrush, _startPosX + 105, _startPosY + 3, 29, 3); g.FillRectangle(additionalBrush, _startPosX + 105, _startPosY + 3, 29, 3);
g.FillRectangle(blackColorBrush, _startPosX + 135, _startPosY, 15, 8); g.FillRectangle(blackColorBrush, _startPosX + 135, _startPosY, 15, 8);
} }
base.DrawTransport(g);
} }
} }
} }

View File

@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectTank.Entities
{
/// <summary>
/// Класс-сущность "Бронирванный транспорт"
/// </summary>
public class EntityArmoredTransport
{
/// <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 double Step => (double)Speed * 100 / Weight;
/// <summary>
/// Конструктор с параметрами
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Основной цвет</param>
public EntityArmoredTransport(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}
}

View File

@ -1,48 +1,29 @@
using System; using ProjectTank.Entities;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace ProjectTank namespace ProjectTank.Entities
{ {
public class EntityTank /// <summary>
/// Класс-сущность "Танк"
/// </summary>
public class EntityTank : EntityArmoredTransport
{ {
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Пушка
/// </summary>
public bool Gun { get; private set; }
/// <summary>
/// Пулемет
/// </summary>
public bool MachineGun { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; }
/// <summary> /// <summary>
/// Дополнительный цвет (для опциональных элементов) /// Дополнительный цвет (для опциональных элементов)
/// </summary> /// </summary>
public Color AdditionalColor { get; private set; } public Color AdditionalColor { get; private set; }
/// <summary> /// <summary>
/// Расчет шага по карте /// Пушка
/// </summary> /// </summary>
public double Step => (double)Speed * 100 / Weight; public bool Gun { get; private set; }
/// <summary>
/// Пулемет
/// </summary>
public bool MachineGun { get; private set; }
/// <summary> /// <summary>
/// Инициализация полей объекта-класса спортивного автомобиля /// Инициализация полей объекта-класса спортивного автомобиля
/// </summary> /// </summary>
@ -52,13 +33,9 @@ namespace ProjectTank
/// <param name="additionalColor">Дополнительный цвет</param> /// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="gun">Признак наличия пушки</param> /// <param name="gun">Признак наличия пушки</param>
/// <param name="machineGun">Признак наличия пулемета</param> /// <param name="machineGun">Признак наличия пулемета</param>
/// public EntityTank(int speed, double weight, Color bodyColor, Color additionalColor, bool gun,
public void Init(int speed, double weight, bool gun, bool machineGun) : base(speed, weight, bodyColor)
bool machineGun, Color bodyColor, Color additionalColor)
{ {
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor; AdditionalColor = additionalColor;
Gun = gun; Gun = gun;
MachineGun = machineGun; MachineGun = machineGun;

View File

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

View File

@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectTank.MovementStrategy
{
/// <summary>
/// Стратегия перемещения объекта в центр экрана
/// </summary>
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.RightBorder <= FieldWidth &&
objParams.RightBorder + GetStep() >= FieldWidth &&
objParams.DownBorder <= FieldHeight &&
objParams.DownBorder + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
var diffX = objParams.RightBorder - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
MoveRight();
}
var diffY = objParams.DownBorder - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
MoveDown();
}
}
}
}

View File

@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectTank.MovementStrategy
{
/// <summary>
/// Стратегия перемещения объекта в центр экрана
/// </summary>
public class MoveToCenter : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.ObjectMiddleHorizontal <= FieldWidth / 2 &&
objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 &&
objParams.ObjectMiddleVertical <= FieldHeight / 2 &&
objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2;
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
var diffX = objParams.ObjectMiddleHorizontal - FieldWidth / 2;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = objParams.ObjectMiddleVertical - FieldHeight / 2;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}
}

View File

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

@ -10,8 +10,10 @@ namespace ProjectTank
[STAThread] [STAThread]
static void Main() static void Main()
{ {
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new TankForm()); Application.Run(new ArmoredTransportCollectionForm());
} }
} }
} }

View File

@ -0,0 +1,99 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectTank.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="armoredTransport">Добавляемый автомобиль</param>
/// <returns></returns>
public int Insert(T armoredTransport)
{
if (_places[Count - 1] != null)
{
return -1;
}
else
{
return Insert(armoredTransport,0);
}
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="car">Добавляемый автомобиль</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public int Insert(T armoredTransport, int position)
{
if (!(position >= 0 && position < Count))
return -1;
if (_places[position] != null)
{
int ind = position;
while (ind < Count && _places[ind] != null)
ind++;
if (ind == Count)
return -1;
for (int i = ind - 1; i >= position; i--)
_places[i + 1] = _places[i];
}
_places[position] = armoredTransport;
return position;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public bool Remove(int position)
{
if (!(position >= 0 && position < Count) || _places[position] == null)
{
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,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectTank.MovementStrategy
{
/// <summary>
/// Статус выполнения операции перемещения
/// </summary>
public enum Status
{
NotInit,
InProgress,
Finish
}
}

View File

@ -35,6 +35,10 @@
this.buttonLeft = new System.Windows.Forms.Button(); this.buttonLeft = new System.Windows.Forms.Button();
this.buttonDown = new System.Windows.Forms.Button(); this.buttonDown = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label();
this.comboBoxStrategy = new System.Windows.Forms.ComboBox();
this.ButtonCreateArmoredTransport = new System.Windows.Forms.Button();
this.ButtonStep = new System.Windows.Forms.Button();
this.ButtonSelectArmoredTransport = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxTanks)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxTanks)).BeginInit();
this.SuspendLayout(); this.SuspendLayout();
// //
@ -42,7 +46,7 @@
// //
this.pictureBoxTanks.Dock = System.Windows.Forms.DockStyle.Fill; this.pictureBoxTanks.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBoxTanks.Location = new System.Drawing.Point(0, 0); this.pictureBoxTanks.Location = new System.Drawing.Point(0, 0);
this.pictureBoxTanks.Margin = new System.Windows.Forms.Padding(6, 6, 6, 6); this.pictureBoxTanks.Margin = new System.Windows.Forms.Padding(6);
this.pictureBoxTanks.Name = "pictureBoxTanks"; this.pictureBoxTanks.Name = "pictureBoxTanks";
this.pictureBoxTanks.Size = new System.Drawing.Size(1445, 881); this.pictureBoxTanks.Size = new System.Drawing.Size(1445, 881);
this.pictureBoxTanks.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; this.pictureBoxTanks.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
@ -53,11 +57,11 @@
// //
this.ButtonCreateTank.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.ButtonCreateTank.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.ButtonCreateTank.Location = new System.Drawing.Point(22, 806); this.ButtonCreateTank.Location = new System.Drawing.Point(22, 806);
this.ButtonCreateTank.Margin = new System.Windows.Forms.Padding(6, 6, 6, 6); this.ButtonCreateTank.Margin = new System.Windows.Forms.Padding(6);
this.ButtonCreateTank.Name = "ButtonCreateTank"; this.ButtonCreateTank.Name = "ButtonCreateTank";
this.ButtonCreateTank.Size = new System.Drawing.Size(139, 49); this.ButtonCreateTank.Size = new System.Drawing.Size(192, 49);
this.ButtonCreateTank.TabIndex = 1; this.ButtonCreateTank.TabIndex = 1;
this.ButtonCreateTank.Text = "Создать"; this.ButtonCreateTank.Text = "Создать Танк";
this.ButtonCreateTank.UseVisualStyleBackColor = true; this.ButtonCreateTank.UseVisualStyleBackColor = true;
this.ButtonCreateTank.Click += new System.EventHandler(this.ButtonCreateTank_Click); this.ButtonCreateTank.Click += new System.EventHandler(this.ButtonCreateTank_Click);
// //
@ -67,7 +71,7 @@
this.buttonUp.BackgroundImage = global::ProjectTank.Properties.Resources.btnUp; this.buttonUp.BackgroundImage = global::ProjectTank.Properties.Resources.btnUp;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.buttonUp.Location = new System.Drawing.Point(1300, 730); this.buttonUp.Location = new System.Drawing.Point(1300, 730);
this.buttonUp.Margin = new System.Windows.Forms.Padding(6, 6, 6, 6); this.buttonUp.Margin = new System.Windows.Forms.Padding(6);
this.buttonUp.Name = "buttonUp"; this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(56, 64); this.buttonUp.Size = new System.Drawing.Size(56, 64);
this.buttonUp.TabIndex = 2; this.buttonUp.TabIndex = 2;
@ -80,7 +84,7 @@
this.buttonRight.BackgroundImage = global::ProjectTank.Properties.Resources.btnRight; this.buttonRight.BackgroundImage = global::ProjectTank.Properties.Resources.btnRight;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.buttonRight.Location = new System.Drawing.Point(1367, 806); this.buttonRight.Location = new System.Drawing.Point(1367, 806);
this.buttonRight.Margin = new System.Windows.Forms.Padding(6, 6, 6, 6); this.buttonRight.Margin = new System.Windows.Forms.Padding(6);
this.buttonRight.Name = "buttonRight"; this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(56, 64); this.buttonRight.Size = new System.Drawing.Size(56, 64);
this.buttonRight.TabIndex = 3; this.buttonRight.TabIndex = 3;
@ -93,7 +97,7 @@
this.buttonLeft.BackgroundImage = global::ProjectTank.Properties.Resources.btnLeft; this.buttonLeft.BackgroundImage = global::ProjectTank.Properties.Resources.btnLeft;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.buttonLeft.Location = new System.Drawing.Point(1233, 806); this.buttonLeft.Location = new System.Drawing.Point(1233, 806);
this.buttonLeft.Margin = new System.Windows.Forms.Padding(6, 6, 6, 6); this.buttonLeft.Margin = new System.Windows.Forms.Padding(6);
this.buttonLeft.Name = "buttonLeft"; this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(56, 64); this.buttonLeft.Size = new System.Drawing.Size(56, 64);
this.buttonLeft.TabIndex = 4; this.buttonLeft.TabIndex = 4;
@ -106,7 +110,7 @@
this.buttonDown.BackgroundImage = global::ProjectTank.Properties.Resources.btnDown; this.buttonDown.BackgroundImage = global::ProjectTank.Properties.Resources.btnDown;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.buttonDown.Location = new System.Drawing.Point(1300, 806); this.buttonDown.Location = new System.Drawing.Point(1300, 806);
this.buttonDown.Margin = new System.Windows.Forms.Padding(6, 6, 6, 6); this.buttonDown.Margin = new System.Windows.Forms.Padding(6);
this.buttonDown.Name = "buttonDown"; this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(56, 64); this.buttonDown.Size = new System.Drawing.Size(56, 64);
this.buttonDown.TabIndex = 5; this.buttonDown.TabIndex = 5;
@ -122,11 +126,64 @@
this.label1.Size = new System.Drawing.Size(0, 32); this.label1.Size = new System.Drawing.Size(0, 32);
this.label1.TabIndex = 6; this.label1.TabIndex = 6;
// //
// comboBoxStrategy
//
this.comboBoxStrategy.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.comboBoxStrategy.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxStrategy.FormattingEnabled = true;
this.comboBoxStrategy.Items.AddRange(new object[] {
"0",
"1"});
this.comboBoxStrategy.Location = new System.Drawing.Point(1181, 12);
this.comboBoxStrategy.Name = "comboBoxStrategy";
this.comboBoxStrategy.Size = new System.Drawing.Size(242, 40);
this.comboBoxStrategy.TabIndex = 7;
//
// ButtonCreateArmoredTransport
//
this.ButtonCreateArmoredTransport.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.ButtonCreateArmoredTransport.Location = new System.Drawing.Point(241, 806);
this.ButtonCreateArmoredTransport.Margin = new System.Windows.Forms.Padding(6);
this.ButtonCreateArmoredTransport.Name = "ButtonCreateArmoredTransport";
this.ButtonCreateArmoredTransport.Size = new System.Drawing.Size(401, 49);
this.ButtonCreateArmoredTransport.TabIndex = 8;
this.ButtonCreateArmoredTransport.Text = "Создать Бронированную машину";
this.ButtonCreateArmoredTransport.UseVisualStyleBackColor = true;
this.ButtonCreateArmoredTransport.Click += new System.EventHandler(this.ButtonCreateArmoredTransport_Click);
//
// ButtonStep
//
this.ButtonStep.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.ButtonStep.Location = new System.Drawing.Point(1263, 61);
this.ButtonStep.Margin = new System.Windows.Forms.Padding(6);
this.ButtonStep.Name = "ButtonStep";
this.ButtonStep.Size = new System.Drawing.Size(160, 49);
this.ButtonStep.TabIndex = 9;
this.ButtonStep.Text = "Шаг";
this.ButtonStep.UseVisualStyleBackColor = true;
this.ButtonStep.Click += new System.EventHandler(this.ButtonStep_Click);
//
// ButtonSelectArmoredTransport
//
this.ButtonSelectArmoredTransport.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.ButtonSelectArmoredTransport.Location = new System.Drawing.Point(664, 806);
this.ButtonSelectArmoredTransport.Margin = new System.Windows.Forms.Padding(6);
this.ButtonSelectArmoredTransport.Name = "ButtonSelectArmoredTransport";
this.ButtonSelectArmoredTransport.Size = new System.Drawing.Size(227, 49);
this.ButtonSelectArmoredTransport.TabIndex = 10;
this.ButtonSelectArmoredTransport.Text = "Выбор";
this.ButtonSelectArmoredTransport.UseVisualStyleBackColor = true;
this.ButtonSelectArmoredTransport.Click += new System.EventHandler(this.ButtonSelectArmoredTransport_Click);
//
// TankForm // TankForm
// //
this.AutoScaleDimensions = new System.Drawing.SizeF(13F, 32F); this.AutoScaleDimensions = new System.Drawing.SizeF(13F, 32F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1445, 881); this.ClientSize = new System.Drawing.Size(1445, 881);
this.Controls.Add(this.ButtonSelectArmoredTransport);
this.Controls.Add(this.ButtonStep);
this.Controls.Add(this.ButtonCreateArmoredTransport);
this.Controls.Add(this.comboBoxStrategy);
this.Controls.Add(this.label1); this.Controls.Add(this.label1);
this.Controls.Add(this.buttonDown); this.Controls.Add(this.buttonDown);
this.Controls.Add(this.buttonLeft); this.Controls.Add(this.buttonLeft);
@ -134,7 +191,7 @@
this.Controls.Add(this.buttonUp); this.Controls.Add(this.buttonUp);
this.Controls.Add(this.ButtonCreateTank); this.Controls.Add(this.ButtonCreateTank);
this.Controls.Add(this.pictureBoxTanks); this.Controls.Add(this.pictureBoxTanks);
this.Margin = new System.Windows.Forms.Padding(6, 6, 6, 6); this.Margin = new System.Windows.Forms.Padding(6);
this.Name = "TankForm"; this.Name = "TankForm";
this.Text = "Tank"; this.Text = "Tank";
((System.ComponentModel.ISupportInitialize)(this.pictureBoxTanks)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxTanks)).EndInit();
@ -151,5 +208,9 @@
private Button buttonDown; private Button buttonDown;
public PictureBox pictureBoxTanks; public PictureBox pictureBoxTanks;
private Label label1; private Label label1;
private ComboBox comboBoxStrategy;
private Button ButtonCreateArmoredTransport;
private Button ButtonStep;
private Button ButtonSelectArmoredTransport;
} }
} }

View File

@ -1,4 +1,6 @@
using System.Reflection.Emit; using System.Reflection.Emit;
using ProjectTank.DrawningObjects;
using ProjectTank.MovementStrategy;
namespace ProjectTank namespace ProjectTank
{ {
@ -10,26 +12,36 @@ namespace ProjectTank
/// <summary> /// <summary>
/// Ïîëå-îáúåêò äëÿ ïðîðèñîâêè îáúåêòà /// Ïîëå-îáúåêò äëÿ ïðîðèñîâêè îáúåêòà
/// </summary> /// </summary>
private DrawningTank? _drawningTank; private DrawningArmoredTransport? _drawningArmoredTransport;
/// <summary>
/// Ñòðàòåãèÿ ïåðåìåùåíèÿ
/// </summary>
private AbstractStrategy? _abstractStrategy;
/// <summary>
/// Âûáðàííûé àâòîìîáèëü
/// </summary>
public DrawningArmoredTransport? SelectedArmoredTransport { get; private set; }
/// <summary> /// <summary>
/// Èíèöèàëèçàöèÿ ôîðìû /// Èíèöèàëèçàöèÿ ôîðìû
/// </summary> /// </summary>
public TankForm() public TankForm()
{ {
InitializeComponent(); InitializeComponent();
_abstractStrategy = null;
SelectedArmoredTransport = null;
} }
/// <summary> /// <summary>
/// Ìåòîä ïðîðèñîâêè ìàøèíû /// Ìåòîä ïðîðèñîâêè ìàøèíû
/// </summary> /// </summary>
private void Draw() private void Draw()
{ {
if (_drawningTank == null) if (_drawningArmoredTransport == null)
{ {
return; return;
} }
Bitmap bmp = new(pictureBoxTanks.Width, pictureBoxTanks.Height); Bitmap bmp = new(pictureBoxTanks.Width, pictureBoxTanks.Height);
Graphics gr = Graphics.FromImage(bmp); Graphics gr = Graphics.FromImage(bmp);
_drawningTank.DrawTransport(gr); _drawningArmoredTransport.DrawTransport(gr);
pictureBoxTanks.Image = bmp; pictureBoxTanks.Image = bmp;
} }
/// <summary> /// <summary>
@ -40,12 +52,43 @@ namespace ProjectTank
private void ButtonCreateTank_Click(object sender, EventArgs e) private void ButtonCreateTank_Click(object sender, EventArgs e)
{ {
Random random = new(); Random random = new();
_drawningTank = new DrawningTank(); Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
_drawningTank.Init(random.Next(100, 300), random.Next(1000, 3000), Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), ColorDialog dialogMain = new();
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), if (dialogMain.ShowDialog() == DialogResult.OK)
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)), {
pictureBoxTanks.Width, pictureBoxTanks.Height); color = dialogMain.Color;
_drawningTank.SetPosition(random.Next(0, 100), random.Next(0, 100)); }
Color dopColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
ColorDialog dialogDop = new();
if (dialogDop.ShowDialog() == DialogResult.OK)
{
dopColor = dialogDop.Color;
}
_drawningArmoredTransport = new DrawningTank(random.Next(100, 300), random.Next(1000, 3000),
color, dopColor,Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)),
pictureBoxTanks.Width, pictureBoxTanks.Height);
_drawningArmoredTransport.SetPosition(random.Next(0, 100), random.Next(0, 100));
Draw();
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü àâòîìîáèëü"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateArmoredTransport_Click(object sender, EventArgs e)
{
Random random = new();
Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
//TODO âûáîð îñíîâíîãî öâåòà
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
_drawningArmoredTransport = new DrawningArmoredTransport(random.Next(100, 300),random.Next(1000, 3000), color,
pictureBoxTanks.Width, pictureBoxTanks.Height);
_drawningArmoredTransport.SetPosition(random.Next(10, 100), random.Next(10,100));
Draw(); Draw();
} }
/// <summary> /// <summary>
@ -55,7 +98,7 @@ namespace ProjectTank
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e) private void ButtonMove_Click(object sender, EventArgs e)
{ {
if (_drawningTank == null) if (_drawningArmoredTransport == null)
{ {
return; return;
} }
@ -63,19 +106,69 @@ namespace ProjectTank
switch (name) switch (name)
{ {
case "buttonUp": case "buttonUp":
_drawningTank.MoveTransport(DirectionType.Up); _drawningArmoredTransport.MoveTransport(DirectionType.Up);
break; break;
case "buttonDown": case "buttonDown":
_drawningTank.MoveTransport(DirectionType.Down); _drawningArmoredTransport.MoveTransport(DirectionType.Down);
break; break;
case "buttonLeft": case "buttonLeft":
_drawningTank.MoveTransport(DirectionType.Left); _drawningArmoredTransport.MoveTransport(DirectionType.Left);
break; break;
case "buttonRight": case "buttonRight":
_drawningTank.MoveTransport(DirectionType.Right); _drawningArmoredTransport.MoveTransport(DirectionType.Right);
break; break;
} }
Draw(); Draw();
} }
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Øàã"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonStep_Click(object sender, EventArgs e)
{
if (_drawningArmoredTransport == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_abstractStrategy = comboBoxStrategy.SelectedIndex
switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(_drawningArmoredTransport.GetMoveableObject,
pictureBoxTanks.Width, pictureBoxTanks.Height);
}
if (_abstractStrategy == null)
{
return;
}
comboBoxStrategy.Enabled = false;
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_abstractStrategy = null;
}
}
/// <summary>
/// Âûáîð àâòîìîáèëÿ
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSelectArmoredTransport_Click(object sender, EventArgs e)
{
SelectedArmoredTransport = _drawningArmoredTransport;
DialogResult = DialogResult.OK;
}
} }
} }