Лабораторная работа №3

This commit is contained in:
vettaql 2024-04-11 11:07:17 +04:00
parent 3c4acc7ca4
commit efebd664ba
12 changed files with 913 additions and 111 deletions

View File

@ -0,0 +1,116 @@
using ProjectTank.Drawnings;
namespace ProjectTank.CollectionGenericObjects;
/// <summary>
/// Абстракция компании, хранящий коллекцию автомобилей
/// </summary>
public abstract class AbstractCompany
{
/// <summary>
/// Размер места (ширина)
/// </summary>
protected readonly int _placeSizeWidth = 210;
/// <summary>
/// Размер места (высота)
/// </summary>
protected readonly int _placeSizeHeight = 80;
/// <summary>
/// Ширина окна
/// </summary>
protected readonly int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
protected readonly int _pictureHeight;
/// <summary>
/// Коллекция поездов
/// </summary>
protected ICollectionGenericObjects<DrawningTank2>? _collection = null;
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth">Ширина окна</param>
/// <param name="picHeight">Высота окна</param>
/// <param name="collection">Коллекция поездов</param>
public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects<DrawningTank2> collection)
{
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.SetMaxCount = GetMaxCount;
}
/// <summary>
/// Перегрузка оператора сложения для класса
/// </summary>
/// <param name="company">Компания</param>
/// <param name="tank">Добавляемый объект</param>
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningTank2 tank)
{
return company._collection.Insert(tank);
}
/// <summary>
/// Перегрузка оператора удаления для класса
/// </summary>
/// <param name="company">Компания</param>
/// <param name="position">Номер удаляемого объекта</param>
/// <returns></returns>
public static DrawningTank2? operator -(AbstractCompany company, int position)
{
return company._collection?.Remove(position);
}
/// <summary>
/// Получение случайного объекта из коллекции
/// </summary>
/// <returns></returns>
public DrawningTank2? GetRandomObject()
{
Random rnd = new();
return _collection?.Get(rnd.Next(GetMaxCount));
}
/// <summary>
/// Вывод всей коллекции
/// </summary>
/// <returns></returns>
public Bitmap? Show()
{
Bitmap bitmap = new(_pictureWidth, _pictureHeight);
Graphics graphics = Graphics.FromImage(bitmap);
DrawBackgound(graphics);
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
DrawningTank2? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
return bitmap;
}
/// <summary>
/// Вывод заднего фона
/// </summary>
/// <param name="g"></param>
protected abstract void DrawBackgound(Graphics g);
/// <summary>
/// Расстановка объектов
/// </summary>
protected abstract void SetObjectsPosition();
}

View File

@ -0,0 +1,48 @@
namespace ProjectTank.CollectionGenericObjects;
/// <summary>
/// Интерфейс описания действий для набора хранимых объектов
/// </summary>
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
public interface ICollectionGenericObjects<T>
where T : class
{
/// <summary>
/// Количество объектов в коллекции
/// </summary>
int Count { get; }
/// <summary>
/// Установка максимального количества элементов
/// </summary>
int SetMaxCount { set; }
/// <summary>
/// Добавление объекта в коллекцию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj);
/// <summary>
/// Добавление объекта в коллекцию на конкретную позицию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
/// </summary>
/// <param name="position">Позиция</param>
/// <returns>true - удаление прошло удачно, false - удаление не удалось</returns>
T? Remove(int position);
/// <summary>
/// Получение объекта по позиции
/// </summary>
/// <param name="position">Позиция</param>
/// <returns>Объект</returns>
T? Get(int position);
}

View File

@ -0,0 +1,136 @@
using System.Runtime.Remoting;
using ProjectTank.Drawnings;
namespace ProjectTank.CollectionGenericObjects;
internal class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
{
/// <summary>
/// Массив объектов, которые храним
/// </summary>
private T?[] _collection;
public int Count => _collection.Length;
public int SetMaxCount
{
set
{
if (value > 0)
{
if (_collection.Length > 0)
{
Array.Resize(ref _collection, value);
}
else
{
_collection = new T?[value];
}
}
}
}
/// <summary>
/// Конструктор
/// </summary>
public MassiveGenericObjects()
{
_collection = Array.Empty<T?>();
}
public T? Get(int position)
{
if (position >= 0 && position < Count)
{
return _collection[position];
}
return null;
}
public int Insert(T obj)
{
// вставка в свободное место набора
for (int i = 0; i < Count; i++)
{
if (_collection[i] == null)
{
_collection[i] = obj;
return i;
}
}
return -1;
}
public int Insert(T obj, int position)
{
// проверка позиции
if (position < 0 || position >= Count)
{
return -1;
}
// проверка, что элемент массива по этой позиции пустой, если нет, то
// ищется свободное место после этой позиции и идет вставка туда
// если нет после, ищем до
if (_collection[position] != null)
{
bool pushed = false;
for (int index = position + 1; index < Count; index++)
{
if (_collection[index] == null)
{
position = index;
pushed = true;
break;
}
}
if (!pushed)
{
for (int index = position - 1; index >= 0; index--)
{
if (_collection[index] == null)
{
position = index;
pushed = true;
break;
}
}
}
if (!pushed)
{
return position;
}
}
// вставка
_collection[position] = obj;
return position;
}
public T? Remove(int position)
{
// проверка позиции
if (position < 0 || position >= Count)
{
return null;
}
if (_collection[position] == null) return null;
T? temp = _collection[position];
_collection[position] = null;
return temp;
}
}

View File

@ -0,0 +1,55 @@
using ProjectTank.Drawnings;
using ProjectTank.Entities;
using System;
namespace ProjectTank.CollectionGenericObjects;
/// <summary>
/// Реализация абстрактной компании - аренда поезда
/// </summary>
public class TankBase : AbstractCompany
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
/// <param name="collection"></param>
public TankBase(int picWidth, int picHeight, ICollectionGenericObjects<DrawningTank2> collection) : base(picWidth, picHeight, collection)
{
}
protected override void DrawBackgound(Graphics g)
{
Pen pen = new(Color.Black);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight; j++)
{
g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * j), new((int)(_placeSizeWidth * (i + 0.5f)), _placeSizeHeight * j));
g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * j), new(_placeSizeWidth * i, _placeSizeHeight * (j + 1)));
}
g.DrawLine(pen, new(_placeSizeWidth * i, _placeSizeHeight * (_pictureHeight / _placeSizeHeight)), new((int)(_placeSizeWidth * (i + 0.5f)), _placeSizeHeight * (_pictureHeight / _placeSizeHeight)));
}
}
protected override void SetObjectsPosition()
{
int n = 0;
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight; j++)
{
DrawningTank2? drawningTank2 = _collection?.Get(n);
n++;
if (drawningTank2 != null)
{
drawningTank2.SetPictureSize(_pictureWidth, _pictureHeight);
drawningTank2.SetPosition(i * _placeSizeWidth + 5, j * _placeSizeHeight + 5);
}
}
}
}
}

View File

@ -40,19 +40,19 @@ public class DrawningTank : DrawningTank2
if (tank.GunTurret) if (tank.GunTurret)
{ {
g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 42, 85, 8); g.DrawRectangle(pen, _startPosX.Value, _startPosY.Value + 17, 85, 8);
g.FillRectangle(additionalBrush, _startPosX.Value, _startPosY.Value + 42, 85, 8); g.FillRectangle(additionalBrush, _startPosX.Value, _startPosY.Value + 17, 85, 8);
} }
if (tank.MachineGun) if (tank.MachineGun)
{ {
g.DrawRectangle(pen, _startPosX.Value + 101, _startPosY.Value + 27, 24, 12); g.DrawRectangle(pen, _startPosX.Value + 101, _startPosY.Value + 3, 24, 12);
g.DrawRectangle(pen, _startPosX.Value + 109, _startPosY.Value + 9, 5, 18); g.DrawRectangle(pen, _startPosX.Value + 109, _startPosY.Value + -14, 5, 18);
g.DrawRectangle(pen, _startPosX.Value + 91, _startPosY.Value + 13, 19, 5); g.DrawRectangle(pen, _startPosX.Value + 91, _startPosY.Value + -12, 19, 5);
g.FillRectangle(additionalBrush, _startPosX.Value + 101, _startPosY.Value + 27, 24, 12); g.FillRectangle(additionalBrush, _startPosX.Value + 101, _startPosY.Value + 3, 24, 12);
g.FillRectangle(additionalBrush, _startPosX.Value + 109, _startPosY.Value + 9, 5, 18); g.FillRectangle(additionalBrush, _startPosX.Value + 109, _startPosY.Value + -14, 5, 18);
g.FillRectangle(additionalBrush, _startPosX.Value + 91, _startPosY.Value + 13, 19, 5); g.FillRectangle(additionalBrush, _startPosX.Value + 91, _startPosY.Value + -12, 19, 5);
} }

View File

@ -195,33 +195,33 @@ public class DrawningTank2
Pen pen = new(Color.Black); Pen pen = new(Color.Black);
//границы танка + гусеницы + пулемёт + башня с оружием //границы танка + гусеницы + пулемёт + башня с оружием
g.DrawRectangle(pen, _startPosX.Value + 48, _startPosY.Value + 39, 55, 17); g.DrawRectangle(pen, _startPosX.Value + 48, _startPosY.Value + 16, 55, 17);
g.DrawRectangle(pen, _startPosX.Value + 12, _startPosY.Value + 56, 137, 13); g.DrawRectangle(pen, _startPosX.Value + 12, _startPosY.Value + 31, 137, 13);
g.DrawEllipse(pen, _startPosX.Value, _startPosY.Value + 59, 160, 35); g.DrawEllipse(pen, _startPosX.Value, _startPosY.Value + 34, 160, 35);
g.DrawEllipse(pen, _startPosX.Value + 51, _startPosY.Value + 65, 29, 23); g.DrawEllipse(pen, _startPosX.Value + 51, _startPosY.Value + 38, 29, 23);
g.DrawEllipse(pen, _startPosX.Value + 111, _startPosY.Value + 65, 29, 23); g.DrawEllipse(pen, _startPosX.Value + 111, _startPosY.Value + 30, 29, 23);
g.DrawEllipse(pen, _startPosX.Value + 91, _startPosY.Value + 73, 18, 15); g.DrawEllipse(pen, _startPosX.Value + 91, _startPosY.Value + 48, 18, 15);
g.DrawEllipse(pen, _startPosX.Value + 71, _startPosY.Value + 73, 18, 15); g.DrawEllipse(pen, _startPosX.Value + 71, _startPosY.Value + 48, 18, 15);
g.DrawEllipse(pen, _startPosX.Value + 51, _startPosY.Value + 73, 18, 15); g.DrawEllipse(pen, _startPosX.Value + 51, _startPosY.Value + 48, 18, 15);
//танк //танк
Brush br = new SolidBrush(EntityTank2.BodyColor); Brush br = new SolidBrush(EntityTank2.BodyColor);
g.FillRectangle(br, _startPosX.Value + 48, _startPosY.Value + 39, 55, 17); g.FillRectangle(br, _startPosX.Value + 48, _startPosY.Value + 14, 55, 17);
g.FillRectangle(br, _startPosX.Value + 12, _startPosY.Value + 56, 137, 13); g.FillRectangle(br, _startPosX.Value + 12, _startPosY.Value + 31, 137, 13);
Brush brDBlue = new SolidBrush(Color.DarkBlue); Brush brDBlue = new SolidBrush(Color.DarkBlue);
g.FillEllipse(brDBlue, _startPosX.Value, _startPosY.Value + 59, 160, 35); g.FillEllipse(brDBlue, _startPosX.Value, _startPosY.Value + 34, 160, 35);
Brush brBlue = new SolidBrush(Color.LightBlue); Brush brBlue = new SolidBrush(Color.LightBlue);
g.FillEllipse(brBlue, _startPosX.Value + 19, _startPosY.Value + 65, 29, 23); g.FillEllipse(brBlue, _startPosX.Value + 19, _startPosY.Value + 40, 29, 23);
g.FillEllipse(brBlue, _startPosX.Value + 111, _startPosY.Value + 65, 29, 23); g.FillEllipse(brBlue, _startPosX.Value + 111, _startPosY.Value + 40, 29, 23);
g.FillEllipse(brBlue, _startPosX.Value + 91, _startPosY.Value + 73, 18, 15); g.FillEllipse(brBlue, _startPosX.Value + 91, _startPosY.Value + 48, 18, 15);
g.FillEllipse(brBlue, _startPosX.Value + 71, _startPosY.Value + 73, 18, 15); g.FillEllipse(brBlue, _startPosX.Value + 71, _startPosY.Value + 48, 18, 15);
g.FillEllipse(brBlue, _startPosX.Value + 51, _startPosY.Value + 73, 18, 15); g.FillEllipse(brBlue, _startPosX.Value + 51, _startPosY.Value + 48, 18, 15);

View File

@ -33,12 +33,10 @@ namespace ProjectTank
private void InitializeComponent() private void InitializeComponent()
{ {
pictureBoxTank = new PictureBox(); pictureBoxTank = new PictureBox();
buttonCreateTank = new Button();
buttonLeft = new Button(); buttonLeft = new Button();
buttonUp = new Button(); buttonUp = new Button();
buttonDown = new Button(); buttonDown = new Button();
buttonRight = new Button(); buttonRight = new Button();
buttonCreateTank2 = new Button();
comboBoxStrategy = new ComboBox(); comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button(); buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxTank).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxTank).BeginInit();
@ -48,30 +46,22 @@ namespace ProjectTank
// //
pictureBoxTank.Dock = DockStyle.Fill; pictureBoxTank.Dock = DockStyle.Fill;
pictureBoxTank.Location = new Point(0, 0); pictureBoxTank.Location = new Point(0, 0);
pictureBoxTank.Margin = new Padding(3, 4, 3, 4);
pictureBoxTank.Name = "pictureBoxTank"; pictureBoxTank.Name = "pictureBoxTank";
pictureBoxTank.Size = new Size(923, 597); pictureBoxTank.Size = new Size(1055, 796);
pictureBoxTank.TabIndex = 0; pictureBoxTank.TabIndex = 0;
pictureBoxTank.TabStop = false; pictureBoxTank.TabStop = false;
// pictureBoxTank.Click += pictureBoxTank_Click;
// buttonCreateTank
//
buttonCreateTank.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateTank.Location = new Point(12, 562);
buttonCreateTank.Name = "buttonCreateTank";
buttonCreateTank.Size = new Size(223, 23);
buttonCreateTank.TabIndex = 1;
buttonCreateTank.Text = "Создать танк с пулемётом";
buttonCreateTank.UseVisualStyleBackColor = true;
buttonCreateTank.Click += ButtonCreateTank_Click;
// //
// buttonLeft // buttonLeft
// //
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = Properties.Resources.Left; buttonLeft.BackgroundImage = Properties.Resources.Left;
buttonLeft.BackgroundImageLayout = ImageLayout.Stretch; buttonLeft.BackgroundImageLayout = ImageLayout.Stretch;
buttonLeft.Location = new Point(787, 550); buttonLeft.Location = new Point(899, 733);
buttonLeft.Margin = new Padding(3, 4, 3, 4);
buttonLeft.Name = "buttonLeft"; buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(35, 35); buttonLeft.Size = new Size(40, 47);
buttonLeft.TabIndex = 2; buttonLeft.TabIndex = 2;
buttonLeft.UseVisualStyleBackColor = true; buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.Click += ButtonMove_Click; buttonLeft.Click += ButtonMove_Click;
@ -81,9 +71,10 @@ namespace ProjectTank
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = Properties.Resources.Up; buttonUp.BackgroundImage = Properties.Resources.Up;
buttonUp.BackgroundImageLayout = ImageLayout.Stretch; buttonUp.BackgroundImageLayout = ImageLayout.Stretch;
buttonUp.Location = new Point(828, 509); buttonUp.Location = new Point(946, 679);
buttonUp.Margin = new Padding(3, 4, 3, 4);
buttonUp.Name = "buttonUp"; buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(35, 35); buttonUp.Size = new Size(40, 47);
buttonUp.TabIndex = 3; buttonUp.TabIndex = 3;
buttonUp.UseVisualStyleBackColor = true; buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += ButtonMove_Click; buttonUp.Click += ButtonMove_Click;
@ -93,9 +84,10 @@ namespace ProjectTank
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = Properties.Resources.Down; buttonDown.BackgroundImage = Properties.Resources.Down;
buttonDown.BackgroundImageLayout = ImageLayout.Stretch; buttonDown.BackgroundImageLayout = ImageLayout.Stretch;
buttonDown.Location = new Point(828, 550); buttonDown.Location = new Point(946, 733);
buttonDown.Margin = new Padding(3, 4, 3, 4);
buttonDown.Name = "buttonDown"; buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(35, 35); buttonDown.Size = new Size(40, 47);
buttonDown.TabIndex = 4; buttonDown.TabIndex = 4;
buttonDown.UseVisualStyleBackColor = true; buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += ButtonMove_Click; buttonDown.Click += ButtonMove_Click;
@ -105,39 +97,31 @@ namespace ProjectTank
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = Properties.Resources.Right; buttonRight.BackgroundImage = Properties.Resources.Right;
buttonRight.BackgroundImageLayout = ImageLayout.Stretch; buttonRight.BackgroundImageLayout = ImageLayout.Stretch;
buttonRight.Location = new Point(869, 550); buttonRight.Location = new Point(993, 733);
buttonRight.Margin = new Padding(3, 4, 3, 4);
buttonRight.Name = "buttonRight"; buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(35, 35); buttonRight.Size = new Size(40, 47);
buttonRight.TabIndex = 5; buttonRight.TabIndex = 5;
buttonRight.UseVisualStyleBackColor = true; buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click; buttonRight.Click += ButtonMove_Click;
// //
// buttonCreateTank2
//
buttonCreateTank2.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateTank2.Location = new Point(250, 562);
buttonCreateTank2.Name = "buttonCreateTank2";
buttonCreateTank2.Size = new Size(223, 23);
buttonCreateTank2.TabIndex = 6;
buttonCreateTank2.Text = "Создать обычный танк";
buttonCreateTank2.UseVisualStyleBackColor = true;
buttonCreateTank2.Click += ButtonCreateTank2_Click;
//
// comboBoxStrategy // comboBoxStrategy
// //
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList; comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true; comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" }); comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(790, 12); comboBoxStrategy.Location = new Point(903, 16);
comboBoxStrategy.Margin = new Padding(3, 4, 3, 4);
comboBoxStrategy.Name = "comboBoxStrategy"; comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(121, 23); comboBoxStrategy.Size = new Size(138, 28);
comboBoxStrategy.TabIndex = 7; comboBoxStrategy.TabIndex = 7;
// //
// buttonStrategyStep // buttonStrategyStep
// //
buttonStrategyStep.Location = new Point(836, 41); buttonStrategyStep.Location = new Point(955, 55);
buttonStrategyStep.Margin = new Padding(3, 4, 3, 4);
buttonStrategyStep.Name = "buttonStrategyStep"; buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(75, 23); buttonStrategyStep.Size = new Size(86, 31);
buttonStrategyStep.TabIndex = 8; buttonStrategyStep.TabIndex = 8;
buttonStrategyStep.Text = "Шаг"; buttonStrategyStep.Text = "Шаг";
buttonStrategyStep.UseVisualStyleBackColor = true; buttonStrategyStep.UseVisualStyleBackColor = true;
@ -145,18 +129,17 @@ namespace ProjectTank
// //
// FormTank // FormTank
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(923, 597); ClientSize = new Size(1055, 796);
Controls.Add(buttonStrategyStep); Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy); Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateTank2);
Controls.Add(buttonRight); Controls.Add(buttonRight);
Controls.Add(buttonDown); Controls.Add(buttonDown);
Controls.Add(buttonUp); Controls.Add(buttonUp);
Controls.Add(buttonLeft); Controls.Add(buttonLeft);
Controls.Add(buttonCreateTank);
Controls.Add(pictureBoxTank); Controls.Add(pictureBoxTank);
Margin = new Padding(3, 4, 3, 4);
Name = "FormTank"; Name = "FormTank";
Text = "Танк с пулемётом"; Text = "Танк с пулемётом";
((System.ComponentModel.ISupportInitialize)pictureBoxTank).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxTank).EndInit();
@ -166,12 +149,10 @@ namespace ProjectTank
#endregion #endregion
private PictureBox pictureBoxTank; private PictureBox pictureBoxTank;
private Button buttonCreateTank;
private Button buttonLeft; private Button buttonLeft;
private Button buttonUp; private Button buttonUp;
private Button buttonDown; private Button buttonDown;
private Button buttonRight; private Button buttonRight;
private Button buttonCreateTank2;
private ComboBox comboBoxStrategy; private ComboBox comboBoxStrategy;
private Button buttonStrategyStep; private Button buttonStrategyStep;
} }

View File

@ -14,6 +14,21 @@ public partial class FormTank : Form
/// </summary> /// </summary>
private AbstractStrategy? _strategy; private AbstractStrategy? _strategy;
/// <summary>
/// Получение объекта
/// </summary>
public DrawningTank2 SetTank
{
set
{
_drawningTank2 = value;
_drawningTank2.SetPictureSize(pictureBoxTank.Width, pictureBoxTank.Height);
comboBoxStrategy.Enabled = true;
_strategy = null;
Draw();
}
}
/// <summary> /// <summary>
/// Конструктор формы /// Конструктор формы
/// </summary> /// </summary>
@ -38,48 +53,6 @@ public partial class FormTank : Form
pictureBoxTank.Image = bmp; pictureBoxTank.Image = bmp;
} }
/// <summary>
/// Создание объекта класса-перемещения
/// </summary>
/// <param name="type">Тип создаваемого объекта</param>
private void CreateObject(string type)
{
Random random = new();
switch (type)
{
case nameof(DrawningTank2):
_drawningTank2 = new DrawningTank2(random.Next(100, 300), random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)));
break;
case nameof(DrawningTank):
_drawningTank2 = 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)),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
break;
default:
return;
}
_drawningTank2.SetPictureSize(pictureBoxTank.Width, pictureBoxTank.Height);
_drawningTank2.SetPosition(random.Next(10, 100), random.Next(10, 100));
_strategy = null;
comboBoxStrategy.Enabled = true;
Draw();
}
/// <summary>
/// Обработка нажатия кнопки "Создать танк с пулемётом"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateTank_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningTank));
/// <summary>
/// Обработка нажатия кнопки "Создать обычный танк"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateTank2_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningTank2));
/// <summary> /// <summary>
/// Перемещение объекта по форме (нажатие кнопок навигации) /// Перемещение объекта по форме (нажатие кнопок навигации)
@ -164,6 +137,11 @@ public partial class FormTank : Form
{ {
} }
private void pictureBoxTank_Click(object sender, EventArgs e)
{
}
} }

View File

@ -0,0 +1,175 @@
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()
{
groupBoxTools = new GroupBox();
comboBoxSelectorCompany = new ComboBox();
buttonAddTank2 = new Button();
buttonAddTank = new Button();
pictureBox = new PictureBox();
maskedTextBox = new MaskedTextBox();
buttonDelTank = new Button();
buttonGoToCheck = new Button();
buttonRefresh = new Button();
groupBoxTools.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
SuspendLayout();
//
// groupBoxTools
//
groupBoxTools.Controls.Add(buttonRefresh);
groupBoxTools.Controls.Add(buttonGoToCheck);
groupBoxTools.Controls.Add(buttonDelTank);
groupBoxTools.Controls.Add(maskedTextBox);
groupBoxTools.Controls.Add(buttonAddTank);
groupBoxTools.Controls.Add(buttonAddTank2);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(931, 0);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(218, 687);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// comboBoxSelectorCompany
//
comboBoxSelectorCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
comboBoxSelectorCompany.Location = new Point(6, 26);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(206, 28);
comboBoxSelectorCompany.TabIndex = 0;
comboBoxSelectorCompany.SelectedIndexChanged += ComboBoxSelectorCompany_SelectedIndexChanged;
//
// buttonAddTank2
//
buttonAddTank2.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddTank2.Location = new Point(6, 111);
buttonAddTank2.Name = "buttonAddTank2";
buttonAddTank2.Size = new Size(206, 49);
buttonAddTank2.TabIndex = 1;
buttonAddTank2.Text = "Добавление бронированной машины";
buttonAddTank2.UseVisualStyleBackColor = true;
buttonAddTank2.Click += ButtonAddTank2_Click;
//
// buttonAddTank
//
buttonAddTank.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddTank.Location = new Point(6, 166);
buttonAddTank.Name = "buttonAddTank";
buttonAddTank.Size = new Size(206, 49);
buttonAddTank.TabIndex = 2;
buttonAddTank.Text = "Добавление танка ";
buttonAddTank.UseVisualStyleBackColor = true;
buttonAddTank.Click += ButtonAddTank_Click;
//
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(931, 687);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
// maskedTextBox
//
maskedTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
maskedTextBox.Location = new Point(6, 276);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(206, 27);
maskedTextBox.TabIndex = 3;
maskedTextBox.ValidatingType = typeof(int);
//
// buttonDelTank
//
buttonDelTank.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonDelTank.Location = new Point(6, 309);
buttonDelTank.Name = "buttonDelTank";
buttonDelTank.Size = new Size(206, 49);
buttonDelTank.TabIndex = 4;
buttonDelTank.Text = "Удалить танка ";
buttonDelTank.UseVisualStyleBackColor = true;
buttonDelTank.Click += ButtonDelTank_Click;
//
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(6, 428);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(206, 49);
buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
buttonGoToCheck.Click += ButtonGoToCheck_Click;
//
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(6, 556);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(206, 49);
buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += ButtonRefresh_Click;
//
// FormTankCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1149, 687);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Name = "FormTankCollection";
Text = "Коллекция танков";
groupBoxTools.ResumeLayout(false);
groupBoxTools.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
ResumeLayout(false);
}
#endregion
private GroupBox groupBoxTools;
private Button buttonAddTank2;
private ComboBox comboBoxSelectorCompany;
private Button buttonAddTank;
private Button buttonDelTank;
private MaskedTextBox maskedTextBox;
private PictureBox pictureBox;
private Button buttonGoToCheck;
private Button buttonRefresh;
}
}

View File

@ -0,0 +1,190 @@
using ProjectTank.CollectionGenericObjects;
using ProjectTank.Drawnings;
using System.Windows.Forms;
namespace ProjectTank;
/// <summary>
/// Форма работы с компанией и ее коллекцией
/// </summary>
public partial class FormTankCollection : Form
{
/// <summary>
/// Компания
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Конструктор
/// </summary>
public FormTankCollection()
{
InitializeComponent();
}
/// <summary>
/// Выбор компании
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new TankBase(pictureBox.Width, pictureBox.Height, new MassiveGenericObjects<DrawningTank2>());
break;
}
}
/// <summary>
/// Добавление обычного автомобиля
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddTank2_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningTank2));
/// <summary>
/// Добавление спортивного автомобиля
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddTank_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningTank));
/// <summary>
/// Создание объекта класса-перемещения
/// </summary>
/// <param name="type">Тип создаваемого объекта</param>
private void CreateObject(string type)
{
if (_company == null)
{
return;
}
Random random = new();
DrawningTank2 drawningTank2;
switch (type)
{
case nameof(DrawningTank2):
drawningTank2 = new DrawningTank2(random.Next(100, 300), random.Next(1000, 3000), GetColor(random));
break;
case nameof(DrawningTank):
// вызов диалогового окна для выбора цвета
drawningTank2 = new DrawningTank(random.Next(100, 300), random.Next(1000, 3000),
GetColor(random),
GetColor(random),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
break;
default:
return;
}
if (_company + drawningTank2 != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
}
else
{
_ = MessageBox.Show(drawningTank2.ToString());
}
}
/// <summary>
/// Получение цвета
/// </summary>
/// <param name="random">Генератор случайных чисел</param>
/// <returns></returns>
private static Color GetColor(Random random)
{
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;
}
return color;
}
/// <summary>
/// Удаление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonDelTank_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
int pos = Convert.ToInt32(maskedTextBox.Text);
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
/// <summary>
/// Передача объекта в другую форму
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonGoToCheck_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
DrawningTank2? tank = null;
int counter = 100;
while (tank == null)
{
tank = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
}
if (tank == null)
{
return;
}
FormTank form = new()
{
SetTank = tank
};
form.ShowDialog();
}
/// <summary>
/// Перерисовка коллекции
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRefresh_Click(object sender, EventArgs e)
{
if (_company == null)
{
return;
}
pictureBox.Image = _company.Show();
}
}

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

@ -1,9 +1,11 @@
using System.Drawing;
namespace ProjectTank namespace ProjectTank
{ {
internal static class Program internal static class Program
{ {
/// <summary> /// <summary>
/// The main entry point for the application. /// The main entry point for the application.
/// </summary> /// </summary>
[STAThread] [STAThread]
static void Main() static void Main()
@ -11,7 +13,8 @@ namespace ProjectTank
// To customize application configuration such as set high DPI settings or default font, // To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new FormTank()); Application.Run(new FormTankCollection());
} }
} }
} }