This commit is contained in:
dyakonovr 2023-10-31 12:26:25 +04:00
parent feac50420c
commit 76dbe4761b
11 changed files with 631 additions and 66 deletions

View File

@ -22,7 +22,7 @@ namespace ProjectTank.DrawningObjects
{
if (EntityTankBase is not EntityTank tank) return;
Pen pen = new(tank.BodyColor);
Pen pen = new(tank.AdditionalColor);
if (tank.TankTower)
{

View File

@ -6,6 +6,7 @@ using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectTank.MovementStrategy;
namespace ProjectTank.DrawningObjects
{
@ -16,13 +17,14 @@ namespace ProjectTank.DrawningObjects
private int pictureHeight;
protected int startPosX;
protected int startPosY;
protected readonly int tankWidth = 150;
protected readonly int tankHeight = 100;
protected readonly int tankWidth = 145;
protected readonly int tankHeight = 95;
public int GetPosX => startPosX;
public int GetPosY => startPosY;
public int GetWidth => tankWidth;
public int GetHeight => tankHeight;
public IMoveableObject GetMoveableObject => new DrawningObjectTank(this);
public DrawningTankBase(int speed, int weight, Color bodyColor, int width, int height)
{
if (width <= tankWidth || height <= tankHeight) return;
@ -31,16 +33,6 @@ namespace ProjectTank.DrawningObjects
pictureHeight = height;
EntityTankBase = new EntityTankBase(speed, weight, bodyColor);
}
protected DrawningTankBase(int speed, int weight, Color bodyColor, int width, int height, int _tankWidth, int _tankHeight)
{
if (width <= tankWidth || height <= tankHeight) return;
pictureWidth = width;
pictureHeight = height;
tankWidth = _tankWidth;
tankHeight = _tankHeight;
EntityTankBase = new EntityTankBase(speed, weight, bodyColor);
}
public bool CanMove(DirectionType direction)
{
if (EntityTankBase == null) return false;
@ -58,9 +50,9 @@ namespace ProjectTank.DrawningObjects
{
if (EntityTankBase == null) return;
startPosX = x;
startPosX = y;
startPosY = y;
if (x + tankWidth >= pictureWidth || y + tankHeight >= pictureHeight)
if (x + tankWidth > pictureWidth || y + tankHeight > pictureHeight)
{
startPosX = 1;
startPosY = 1;
@ -101,25 +93,25 @@ namespace ProjectTank.DrawningObjects
int cornerRadius = 20;
path.AddArc(startPosX, startPosY + 65, cornerRadius, cornerRadius, 180, 90);
path.AddArc(startPosX + 1, startPosY + 65, cornerRadius, cornerRadius, 180, 90);
path.AddArc(startPosX + tankWidth - cornerRadius, startPosY + 65, cornerRadius, cornerRadius, 270, 90);
path.AddArc(startPosX + tankWidth - cornerRadius, startPosY + tankHeight - cornerRadius, cornerRadius, cornerRadius, 0, 90);
path.AddArc(startPosX, startPosY + tankHeight - cornerRadius, cornerRadius, cornerRadius, 90, 90);
path.AddArc(startPosX + 1, startPosY + tankHeight - cornerRadius, cornerRadius, cornerRadius, 90, 90);
path.CloseFigure();
g.DrawPath(pen, path);
// колеса
g.DrawEllipse(pen, startPosX + 1, startPosY + tankHeight - 5 - 25, 25, 25);
g.DrawEllipse(pen, startPosX + 1, startPosY + tankHeight - 3 - 25, 25, 25);
for (int i = 1; i < 5; i++)
{
g.DrawEllipse(pen, startPosX + 30 + 5 * i + 15 * (i - 1), startPosY + tankHeight - 5 - 15, 15, 15);
}
g.DrawEllipse(pen, startPosX + tankWidth - 25 - 1, startPosY + tankHeight - 5 - 25, 25, 25);
g.DrawEllipse(pen, startPosX + tankWidth - 25 - 1, startPosY + tankHeight - 3 - 25, 25, 25);
// башня
SolidBrush brush = new SolidBrush(EntityTankBase.BodyColor);
g.FillRectangle(brush, startPosX + 45, startPosY + 30, 60, 25);
g.FillRectangle(brush, startPosX + 45, startPosY + 30, 60, 26);
g.FillRectangle(brush, startPosX + 5, startPosY + 55 + 1, tankWidth - 10, 9);
}

View File

@ -37,6 +37,7 @@
comboBoxStrategy = new ComboBox();
button1 = new Button();
button2 = new Button();
button3 = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxTank).BeginInit();
SuspendLayout();
//
@ -45,18 +46,18 @@
pictureBoxTank.Dock = DockStyle.Fill;
pictureBoxTank.Location = new Point(0, 0);
pictureBoxTank.Name = "pictureBoxTank";
pictureBoxTank.Size = new Size(991, 458);
pictureBoxTank.Size = new Size(760, 458);
pictureBoxTank.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBoxTank.TabIndex = 7;
pictureBoxTank.TabStop = false;
//
// createButton
//
createButton.Location = new Point(700, 406);
createButton.Location = new Point(403, 406);
createButton.Name = "createButton";
createButton.Size = new Size(130, 41);
createButton.Size = new Size(167, 41);
createButton.TabIndex = 8;
createButton.Text = "Create tank base";
createButton.Text = "Создать основу танка";
createButton.UseVisualStyleBackColor = true;
createButton.Click += ButtonCreateTankBase_Click;
//
@ -113,37 +114,48 @@
comboBoxStrategy.AutoCompleteCustomSource.AddRange(new string[] { "Move to center", "Move to border" });
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "Move to center", "Move to right bottom corner" });
comboBoxStrategy.Location = new Point(757, 0);
comboBoxStrategy.Items.AddRange(new object[] { "Двигаться в центр", "Двигаться в правый нижний угол" });
comboBoxStrategy.Location = new Point(514, 0);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(234, 28);
comboBoxStrategy.TabIndex = 13;
//
// button1
//
button1.Location = new Point(840, 406);
button1.Location = new Point(576, 405);
button1.Name = "button1";
button1.Size = new Size(139, 41);
button1.Size = new Size(172, 41);
button1.TabIndex = 14;
button1.Text = "Create full tank";
button1.Text = "Создать полный танк";
button1.UseVisualStyleBackColor = true;
button1.Click += ButtonCreateTank_Click;
//
// button2
//
button2.Location = new Point(897, 34);
button2.Location = new Point(654, 49);
button2.Name = "button2";
button2.Size = new Size(94, 29);
button2.TabIndex = 15;
button2.Text = "Step";
button2.Text = "Шаг";
button2.UseVisualStyleBackColor = true;
button2.Click += ButtonStep_Click;
//
// button3
//
button3.Location = new Point(277, 406);
button3.Name = "button3";
button3.Size = new Size(120, 41);
button3.TabIndex = 16;
button3.Text = "Выбрать танк";
button3.UseVisualStyleBackColor = true;
button3.Click += ButtonSelectTank_Click;
//
// FormTank
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(991, 458);
ClientSize = new Size(760, 458);
Controls.Add(button3);
Controls.Add(button2);
Controls.Add(button1);
Controls.Add(comboBoxStrategy);
@ -155,7 +167,7 @@
Controls.Add(pictureBoxTank);
Name = "FormTank";
StartPosition = FormStartPosition.CenterScreen;
Text = "Drawing tank";
Text = "Рисунок танка";
((System.ComponentModel.ISupportInitialize)pictureBoxTank).EndInit();
ResumeLayout(false);
PerformLayout();
@ -171,5 +183,6 @@
private ComboBox comboBoxStrategy;
private Button button1;
private Button button2;
private Button button3;
}
}

View File

@ -1,90 +1,124 @@
using ProjectTank;
using ProjectTank.DrawningObjects;
using ProjectTank.Entities;
using ProjectTank.MovementStrategy;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace ProjectTank
{
public partial class FormTank : Form
{
private DrawningTankBase? DrawningTank;
private AbstractStrategy? AbstractStrategy;
private DrawningTankBase? _drawningTank;
private AbstractStrategy? _strategy;
public DrawningTankBase? SelectedTank { get; private set; }
public FormTank()
{
InitializeComponent();
_strategy = null;
SelectedTank = null;
}
private void Draw()
{
if (DrawningTank == null) return;
if (_drawningTank == null) return;
Bitmap bmp = new(pictureBoxTank.Width, pictureBoxTank.Height);
Graphics gr = Graphics.FromImage(bmp);
DrawningTank.DrawTransport(gr);
_drawningTank.DrawTransport(gr);
pictureBoxTank.Image = bmp;
}
private void ButtonCreateTank_Click(object sender, EventArgs e)
{
Random random = new();
DrawningTank = new DrawningTank(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)), true, true, pictureBoxTank.Width, pictureBoxTank.Height);
DrawningTank.SetPosition(random.Next(10, 100), random.Next(10, 100));
Color bodyColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
Color additionalColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
bodyColor = dialog.Color;
if (dialog.ShowDialog() == DialogResult.OK)
additionalColor = dialog.Color;
}
_drawningTank = new DrawningTank(random.Next(100, 300), random.Next(1000, 3000), bodyColor,
additionalColor, Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)), pictureBoxTank.Width, pictureBoxTank.Height);
_drawningTank.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
private void ButtonCreateTankBase_Click(object sender, EventArgs e)
{
Random random = new();
DrawningTank = new DrawningTankBase(random.Next(100, 300), random.Next(1000, 3000), Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), pictureBoxTank.Width, pictureBoxTank.Height);
DrawningTank.SetPosition(random.Next(10, 100), random.Next(10, 100));
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;
}
_drawningTank = new DrawningTankBase(random.Next(100, 300), random.Next(1000, 3000), color,
pictureBoxTank.Width, pictureBoxTank.Height);
_drawningTank.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
private void moveButton_Click(object sender, EventArgs e)
{
if (DrawningTank == null) return;
if (_drawningTank == null) return;
string name = ((System.Windows.Forms.Button)sender)?.Name ?? string.Empty;
string name = ((Button)sender)?.Name ?? string.Empty;
switch (name)
{
case "buttonUp":
DrawningTank.MoveTransport(DirectionType.Up);
_drawningTank.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
DrawningTank.MoveTransport(DirectionType.Down);
_drawningTank.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
DrawningTank.MoveTransport(DirectionType.Left);
_drawningTank.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
DrawningTank.MoveTransport(DirectionType.Right);
_drawningTank.MoveTransport(DirectionType.Right);
break;
}
Draw();
}
private void ButtonStep_Click(object sender, EventArgs e)
{
if (DrawningTank == null) return;
if (_drawningTank == null) return;
if (comboBoxStrategy.Enabled)
{
AbstractStrategy = comboBoxStrategy.SelectedIndex
_strategy = comboBoxStrategy.SelectedIndex
switch
{
0 => new MoveToCenter(),
1 => new MoveToRightBottomCorner(),
_ => null,
};
if (AbstractStrategy == null) return;
AbstractStrategy.SetData(new DrawningObjectTank(DrawningTank), pictureBoxTank.Width, pictureBoxTank.Height);
if (_strategy == null) return;
_strategy.SetData(new DrawningObjectTank(_drawningTank), pictureBoxTank.Width, pictureBoxTank.Height);
comboBoxStrategy.Enabled = false;
}
if (AbstractStrategy == null) return;
if (_strategy == null) return;
AbstractStrategy.MakeStep();
_strategy.MakeStep();
Draw();
if (AbstractStrategy.GetStatus() == MovementStrategy.Status.Finish)
if (_strategy.GetStatus() == MovementStrategy.Status.Finish)
{
comboBoxStrategy.Enabled = true;
AbstractStrategy = null;
_strategy = null;
}
}
private void ButtonSelectTank_Click(object sender, EventArgs e)
{
SelectedTank = _drawningTank;
DialogResult = DialogResult.OK;
}
}
}

121
ProjectTank/FormTankCollection.Designer.cs generated Normal file
View File

@ -0,0 +1,121 @@
namespace ProjectTank
{
partial class FormTankCollection
{
/// <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()
{
pictureBoxCollection = new PictureBox();
label1 = new Label();
button3 = new Button();
button2 = new Button();
button4 = new Button();
maskedTextBoxNumber = new TextBox();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
SuspendLayout();
//
// pictureBoxCollection
//
pictureBoxCollection.Location = new Point(6, 4);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(760, 475);
pictureBoxCollection.TabIndex = 0;
pictureBoxCollection.TabStop = false;
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(775, 9);
label1.Name = "label1";
label1.Size = new Size(103, 20);
label1.TabIndex = 1;
label1.Text = "Инструменты";
//
// button3
//
button3.Location = new Point(775, 247);
button3.Name = "button3";
button3.Size = new Size(139, 29);
button3.TabIndex = 4;
button3.Text = "Обн. коллекцию";
button3.UseVisualStyleBackColor = true;
button3.Click += ButtonRefreshCollection_Click;
//
// button2
//
button2.Location = new Point(775, 166);
button2.Name = "button2";
button2.Size = new Size(139, 29);
button2.TabIndex = 5;
button2.Text = "Удалить танк";
button2.UseVisualStyleBackColor = true;
button2.Click += ButtonRemoveTank_Click;
//
// button4
//
button4.Location = new Point(775, 32);
button4.Name = "button4";
button4.Size = new Size(139, 29);
button4.TabIndex = 6;
button4.Text = "Добавить танк";
button4.UseVisualStyleBackColor = true;
button4.Click += ButtonAddTank_Click;
//
// maskedTextBoxNumber
//
maskedTextBoxNumber.Location = new Point(775, 133);
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(139, 27);
maskedTextBoxNumber.TabIndex = 7;
//
// FormTankCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(926, 486);
Controls.Add(maskedTextBoxNumber);
Controls.Add(button4);
Controls.Add(button2);
Controls.Add(button3);
Controls.Add(label1);
Controls.Add(pictureBoxCollection);
Name = "FormTankCollection";
Text = "Набор танков";
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private PictureBox pictureBoxCollection;
private Label label1;
private Button button3;
private Button button2;
private Button button4;
private TextBox maskedTextBoxNumber;
}
}

View File

@ -0,0 +1,78 @@
using ProjectTank.DrawningObjects;
using ProjectTank.Generics;
using ProjectTank.MovementStrategy;
namespace ProjectTank
{
public partial class FormTankCollection : Form
{
/// <summary>
/// Набор объектов
/// </summary>
private readonly TanksGenericCollection<DrawningTankBase, DrawningObjectTank> _tanks;
/// <summary>
/// Конструктор
/// </summary>
public FormTankCollection()
{
InitializeComponent();
_tanks = new TanksGenericCollection<DrawningTankBase, DrawningObjectTank>(pictureBoxCollection.Width,
pictureBoxCollection.Height);
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddTank_Click(object sender, EventArgs e)
{
FormTank form = new();
if (form.ShowDialog() == DialogResult.OK)
{
if (_tanks + form.SelectedTank != null)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = _tanks.ShowTanks();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
}
/// <summary>
/// Удаление объекта из набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveTank_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();
maskedTextBoxNumber.Text = "";
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
/// <summary>
/// Обновление рисунка по набору
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
{
pictureBoxCollection.Image = _tanks.ShowTanks();
}
}
}

View File

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

View File

@ -0,0 +1,82 @@
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="tank">Добавляемый автомобиль</param>
/// <returns></returns>
public int Insert(T tank)
{
if (_places[Count-1] != null)
return -1;
return Insert(tank, 0);
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="tank">Добавляемый автомобиль</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)
{
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] = tank;
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,132 @@
using ProjectTank.DrawningObjects;
using ProjectTank.MovementStrategy;
namespace ProjectTank.Generics
{
/// <summary>
/// Параметризованный класс для набора объектов DrawningCar
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
internal class TanksGenericCollection<T, U> where T : DrawningTankBase where U : IMoveableObject
{
/// <summary>
/// Ширина окна прорисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна прорисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Размер занимаемого объектом места (ширина)
/// </summary>
private readonly int _placeSizeWidth = 150;
/// <summary>
/// Размер занимаемого объектом места (высота)
/// </summary>
private readonly int _placeSizeHeight = 100;
/// <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) ?? -1;
}
/// <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, j * _placeSizeHeight);
}
g.DrawLine(pen, i * _placeSizeWidth, 0, i * _placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight);
}
}
/// <summary>
/// Метод прорисовки объектов
/// </summary>
/// <param name="g"></param>
private void DrawObjects(Graphics g)
{
for (int i = 0; i < _collection.Count; i++)
{
DrawningTankBase tank = _collection.Get(i);
if (tank != null)
{
int columnsCount = _pictureHeight / _placeSizeHeight + 1;
int colIndex = i % columnsCount;
int rowIndex = i / columnsCount;
tank.SetPosition(colIndex * _placeSizeWidth + 2, rowIndex * _placeSizeHeight + 2);
tank.DrawTransport(g);
}
}
}
}
}

View File

@ -1,11 +1,4 @@
using ProjectTank.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectTank.MovementStrategy
namespace ProjectTank.MovementStrategy
{
public interface IMoveableObject
{

View File

@ -11,7 +11,7 @@ namespace ProjectTank
// 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 FormTankCollection());
}
}
}