Последняя ошибка - добавляет лишние элементы

This commit is contained in:
repka228 2024-03-19 18:04:27 +04:00
parent df565e4295
commit f7e90e6ffa
10 changed files with 132 additions and 124 deletions

View File

@ -9,18 +9,18 @@ namespace AccordionBus.CollectionGenericObjects;
using ProjectAccordionBus.CollectionGenericObjects; using ProjectAccordionBus.CollectionGenericObjects;
/// <summary> /// <summary>
/// Абстракция компании, хранящий коллекцию автомобилей /// Абстракция компании, хранящий коллекцию автобусов
/// </summary> /// </summary>
public abstract class AbstractCompany public abstract class AbstractBusStation
{ {
/// <summary> /// <summary>
/// Размер места (ширина) /// Размер места (ширина)
/// </summary> /// </summary>
protected readonly int _placeSizeWidth = 180; protected readonly int _placeSizeWidth = 215;
/// <summary> /// <summary>
/// Размер места (высота) /// Размер места (высота)
/// </summary> /// </summary>
protected readonly int _placeSizeHeight = 40; protected readonly int _placeSizeHeight = 50;
/// <summary> /// <summary>
/// Ширина окна /// Ширина окна
/// </summary> /// </summary>
@ -36,16 +36,14 @@ public abstract class AbstractCompany
/// <summary> /// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне /// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary> /// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight / private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
(_placeSizeWidth * _placeSizeHeight);
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
/// <param name="picWidth">Ширина окна</param> /// <param name="picWidth">Ширина окна</param>
/// <param name="picHeight">Высота окна</param> /// <param name="picHeight">Высота окна</param>
/// <param name="collection">Коллекция автомобилей</param> /// <param name="collection">Коллекция автомобилей</param>
public AbstractCompany(int picWidth, int picHeight, public AbstractBusStation(int picWidth, int picHeight, ICollectionGenericObjects<DrawningBus> collection)
ICollectionGenericObjects<DrawningBus> collection)
{ {
_pictureWidth = picWidth; _pictureWidth = picWidth;
_pictureHeight = picHeight; _pictureHeight = picHeight;
@ -58,9 +56,9 @@ private int GetMaxCount => _pictureWidth * _pictureHeight /
/// <param name="company">Компания</param> /// <param name="company">Компания</param>
/// <param name="car">Добавляемый объект</param> /// <param name="car">Добавляемый объект</param>
/// <returns></returns> /// <returns></returns>
public static bool operator +(AbstractCompany company, DrawningBus car) public static int operator +(AbstractBusStation company, DrawningBus bus)
{ {
return company._collection?.Insert(car) ?? false; return company._collection.Insert(bus)? 1 : 0;
} }
/// <summary> /// <summary>
/// Перегрузка оператора удаления для класса /// Перегрузка оператора удаления для класса
@ -68,9 +66,9 @@ private int GetMaxCount => _pictureWidth * _pictureHeight /
/// <param name="company">Компания</param> /// <param name="company">Компания</param>
/// <param name="position">Номер удаляемого объекта</param> /// <param name="position">Номер удаляемого объекта</param>
/// <returns></returns> /// <returns></returns>
public static bool operator -(AbstractCompany company, int position) public static DrawningBus operator -(AbstractBusStation company, int position)
{ {
return company._collection?.Remove(position) ?? false; return company._collection?.Remove(position);
} }
/// <summary> /// <summary>
/// Получение случайного объекта из коллекции /// Получение случайного объекта из коллекции

View File

@ -1,31 +0,0 @@
using ProjectAccordionBus.CollectionGenericObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AccordionBus.Drawnings;
namespace AccordionBus.CollectionGenericObjects;
public class BusSharingService : AbstractCompany
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
/// <param name="collection"></param>
public BusSharingService(int picWidth, int picHeight,
ICollectionGenericObjects<DrawningBus> collection) : base(picWidth, picHeight, collection)
{
}
protected override void DrawBackgound(Graphics g)
{
throw new NotImplementedException();
}
protected override void SetObjectsPosition()
{
throw new NotImplementedException();
}
}

View File

@ -0,0 +1,64 @@
using ProjectAccordionBus.CollectionGenericObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AccordionBus.Drawnings;
namespace AccordionBus.CollectionGenericObjects;
public class BusStation : AbstractBusStation
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
/// <param name="collection"></param>
public BusStation(int picWidth, int picHeight,
ICollectionGenericObjects<DrawningBus> collection) : base(picWidth, picHeight, collection)
{
}
protected override void DrawBackgound(Graphics g)
{
Pen pen = new(Color.Black, 3);
int posX = 0;
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
int posY = 0;
g.DrawLine(pen, posX, posY, posX, posY + _placeSizeHeight * (_pictureHeight / _placeSizeHeight));
for (int j = 0; j <= _pictureHeight / _placeSizeHeight; j++)
{
g.DrawLine(pen, posX, posY, posX + _placeSizeWidth - 30, posY);
posY += _placeSizeHeight;
}
posX += _placeSizeWidth;
}
}
protected override void SetObjectsPosition()
{
int posX = _pictureWidth / _placeSizeWidth-1;
int posY = 0;
for (int i = 0; i < _collection?.Count; i++)
{
if (_collection.Get(i) != null)
{
_collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(i)?.SetPosition(posX * _placeSizeWidth+3, posY * _placeSizeHeight+3);
}
if (posX > 0)
{
posX--;
}
else
{
posX = _pictureWidth / _placeSizeWidth - 1;
posY++;
}
if (posY >= _placeSizeHeight) { return; }
}
}
}

View File

@ -26,13 +26,13 @@ where T : class
/// <param name="obj">Добавляемый объект</param> /// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns> /// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
bool Insert(T obj, int position); bool? Insert(T obj, int position);
/// <summary> /// <summary>
/// Удаление объекта из коллекции с конкретной позиции /// Удаление объекта из коллекции с конкретной позиции
/// </summary> /// </summary>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns>true - удаление прошло удачно, false - удаление не удалось</returns> /// <returns>true - удаление прошло удачно, false - удаление не удалось</returns>
bool Remove(int position); T? Remove(int position);
/// <summary> /// <summary>
/// Получение объекта по позиции /// Получение объекта по позиции
/// </summary> /// </summary>

View File

@ -38,13 +38,13 @@ where T : class
{ {
_collection = Array.Empty<T?>(); _collection = Array.Empty<T?>();
} }
public T? Get(int position) public T? Get(int position) // получение с позиции
{ {
if (_collection[position]!=null) if (position < 0 || position >= _collection.Length) // если позиция передано неправильно
return _collection[position]; return null;
return null; return _collection[position];
} }
public bool Insert(T obj) public bool Insert(T obj) // вставка объекта на свободное место
{ {
for(int i=0; i < _collection.Length; ++i) for(int i=0; i < _collection.Length; ++i)
{ {
@ -56,16 +56,18 @@ where T : class
} }
return false; return false;
} }
public bool Insert(T obj, int position) public bool? Insert(T obj, int position) // вставка объекта на место
{ {
if (_collection[position] == null) if (position < 0 || position >= _collection.Length) // если позиция переданна неправильно
return false;
if (_collection[position] == null)//если позиция пуста
{ {
_collection[position] = obj; _collection[position] = obj;
return true; return true;
} }
else else
{ {
for(int i=position; i< _collection.Length; ++i) for(int i=position; i< _collection.Length; ++i) //ищем свободное место справа
{ {
if(_collection[i]==null) if(_collection[i]==null)
{ {
@ -73,7 +75,7 @@ where T : class
return true; return true;
} }
} }
for (int i = 0; i < position; ++i) for (int i = 0; i < position; ++i) // иначе слева
{ {
if (_collection[i] == null) if (_collection[i] == null)
{ {
@ -84,13 +86,13 @@ where T : class
} }
return false; return false;
} }
public bool Remove(int position) public T? Remove(int position) // удаление объекта, зануляя его
{ {
if (_collection[position] != null) if (position < 0 || position >= _collection.Length || _collection[position] == null)
{ return null;
_collection[position] = null; T ?temp = _collection[position];
return true; _collection[position]=null;
} return temp;
return false;
} }
} }

View File

@ -32,7 +32,7 @@ public class DrawningAccordionBus:DrawningBus
/// <param name="speed">скорость</param> /// <param name="speed">скорость</param>
/// <param name="weight">вес</param> /// <param name="weight">вес</param>
/// <param name="bodyColor">основной цвет</param> /// <param name="bodyColor">основной цвет</param>
public DrawningAccordionBus(int speed, double weight, Color bodyColor) : base(180, 40) public DrawningAccordionBus(int speed, double weight, Color bodyColor) : base(220, 50)
{ {
EntityBus = new EntityAccordionBus(speed, weight, bodyColor); EntityBus = new EntityAccordionBus(speed, weight, bodyColor);
} }
@ -48,7 +48,7 @@ public class DrawningAccordionBus:DrawningBus
g.DrawRectangle(new Pen(Color.Black), _startPosX.Value + 70, _startPosY.Value, 40, 30); g.DrawRectangle(new Pen(Color.Black), _startPosX.Value + 70, _startPosY.Value, 40, 30);
g.FillRectangle(new HatchBrush(HatchStyle.Vertical, Color.Black, EntityBus.BodyColor), _startPosX.Value + 70, _startPosY.Value, 40, 30); g.FillRectangle(new HatchBrush(HatchStyle.Vertical, Color.Black, EntityBus.BodyColor), _startPosX.Value + 70, _startPosY.Value, 40, 30);
g.DrawRectangle(new Pen(Color.Black), _startPosX.Value, _startPosY.Value, 70, 30); g.DrawRectangle(new Pen(Color.Black), _startPosX.Value, _startPosY.Value, 70, 30);
g.DrawRectangle(new Pen(Color.Black), _startPosX.Value + 110, _startPosY.Value, 70, 30); g.DrawRectangle(new Pen(Color.Black), _startPosX.Value + 110, _startPosY.Value, 70, 30);
} }
//стекла //стекла
if (accordionBus.BodyGlass) if (accordionBus.BodyGlass)

View File

@ -27,12 +27,10 @@
{ {
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormAccordionBus)); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormAccordionBus));
pictureBoxAccordionBus = new PictureBox(); pictureBoxAccordionBus = new PictureBox();
buttonCreate = new Button();
buttonUp = new Button(); buttonUp = new Button();
buttonLeft = new Button(); buttonLeft = new Button();
buttonDown = new Button(); buttonDown = new Button();
buttonRight = new Button(); buttonRight = new Button();
buttonCreateBus = new Button();
comboBoxStrategy = new ComboBox(); comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button(); buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxAccordionBus).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxAccordionBus).BeginInit();
@ -48,16 +46,6 @@
pictureBoxAccordionBus.TabIndex = 5; pictureBoxAccordionBus.TabIndex = 5;
pictureBoxAccordionBus.TabStop = false; pictureBoxAccordionBus.TabStop = false;
// //
// buttonCreate
//
buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreate.Location = new Point(12, 421);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(216, 23);
buttonCreate.TabIndex = 6;
buttonCreate.Text = "Создать автобус с гармошкой";
buttonCreate.UseVisualStyleBackColor = true;
//
// buttonUp // buttonUp
// //
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
@ -110,16 +98,6 @@
buttonRight.UseVisualStyleBackColor = true; buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click; buttonRight.Click += ButtonMove_Click;
// //
// buttonCreateBus
//
buttonCreateBus.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateBus.Location = new Point(234, 421);
buttonCreateBus.Name = "buttonCreateBus";
buttonCreateBus.Size = new Size(216, 23);
buttonCreateBus.TabIndex = 11;
buttonCreateBus.Text = "Создать автобус";
buttonCreateBus.UseVisualStyleBackColor = true;
//
// comboBoxStrategy // comboBoxStrategy
// //
comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right; comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right;
@ -149,12 +127,10 @@
ClientSize = new Size(800, 450); ClientSize = new Size(800, 450);
Controls.Add(buttonStrategyStep); Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy); Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateBus);
Controls.Add(buttonRight); Controls.Add(buttonRight);
Controls.Add(buttonDown); Controls.Add(buttonDown);
Controls.Add(buttonLeft); Controls.Add(buttonLeft);
Controls.Add(buttonUp); Controls.Add(buttonUp);
Controls.Add(buttonCreate);
Controls.Add(pictureBoxAccordionBus); Controls.Add(pictureBoxAccordionBus);
Name = "FormAccordionBus"; Name = "FormAccordionBus";
Text = "Автобус с гармошкой"; Text = "Автобус с гармошкой";
@ -164,12 +140,10 @@
} }
#endregion #endregion
private PictureBox pictureBoxAccordionBus; private PictureBox pictureBoxAccordionBus;
private Button buttonCreate;
private Button buttonUp; private Button buttonUp;
private Button buttonLeft; private Button buttonLeft;
private Button buttonDown; private Button buttonDown;
private Button buttonRight; private Button buttonRight;
private Button buttonCreateBus;
private ComboBox comboBoxStrategy; private ComboBox comboBoxStrategy;
private Button buttonStrategyStep; private Button buttonStrategyStep;
} }

View File

@ -16,87 +16,92 @@ public partial class FormAccordionBus : Form
/// <summary> /// <summary>
/// Поле-объект для прорисовки объекта /// Поле-объект для прорисовки объекта
/// </summary> /// </summary>
private DrawningBus? _drawningBus; private DrawningBus? _drawningBus;
/// <summary> /// <summary>
/// Стратегия перемещения /// Стратегия перемещения
/// </summary> /// </summary>
private AbstractStrategy? _strategy; private AbstractStrategy? _strategy;
/// <summary>
///<summary> /// Получение объекта
/// Получение объекта /// </summary>
///</summary> public DrawningBus SetBus
public DrawningBus SetBus
{ {
set set
{ {
_drawningBus = value; _drawningBus = value;
_drawningBus.SetPictureSize(pictureBoxAccordionBus.Width, pictureBoxAccordionBus.Height); _drawningBus.SetPictureSize(pictureBoxAccordionBus.Width, pictureBoxAccordionBus.Height);
comboBoxStrategy.Enabled = false; comboBoxStrategy.Enabled = true;
_strategy = null; _strategy = null;
Draw(); Draw();
} }
} }
/// <summary> /// <summary>
/// Конструктор формы /// Инициализация формы
/// </summary> /// </summary>
public FormAccordionBus() public FormAccordionBus()
{ {
InitializeComponent(); InitializeComponent();
_strategy = null; _strategy = null;
} }
/// <summary> /// <summary>
/// Метод прорисовки машины /// Метод прорисовки машины
/// </summary> /// </summary>
private void Draw() private void Draw()
{ {
if (_drawningBus == null) if (_drawningBus == null)
{ {
return; return;
} }
Bitmap bmp = new(pictureBoxAccordionBus.Width,
pictureBoxAccordionBus.Height); Bitmap bmp = new(pictureBoxAccordionBus.Width, pictureBoxAccordionBus.Height);
Graphics gr = Graphics.FromImage(bmp); Graphics gr = Graphics.FromImage(bmp);
_drawningBus.DrawTransport(gr); _drawningBus.DrawTransport(gr);
pictureBoxAccordionBus.Image = bmp; pictureBoxAccordionBus.Image = bmp;
} }
/// <summary> /// <summary>
/// Перемещение объекта по форме (нажатие кнопок навигации) /// Перемещение объекта по форме (нажатие кнопок навигации)
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <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 (_drawningBus == null) if (_drawningBus == null)
{ {
return; return;
} }
string name = ((Button)sender)?.Name ?? string.Empty; string name = ((Button)sender)?.Name ?? string.Empty;
bool result = false; bool result = false;
switch (name) switch (name)
{ {
case "buttonUp": case "buttonUp":
result = result = _drawningBus.MoveTransport(DirectionType.Up);
_drawningBus.MoveTransport(DirectionType.Up);
break; break;
case "buttonDown": case "buttonDown":
result = result = _drawningBus.MoveTransport(DirectionType.Down);
_drawningBus.MoveTransport(DirectionType.Down);
break; break;
case "buttonLeft": case "buttonLeft":
result = result = _drawningBus.MoveTransport(DirectionType.Left);
_drawningBus.MoveTransport(DirectionType.Left);
break; break;
case "buttonRight": case "buttonRight":
result = result = _drawningBus.MoveTransport(DirectionType.Right);
_drawningBus.MoveTransport(DirectionType.Right);
break; break;
} }
if (result) if (result)
{ {
Draw(); Draw();
} }
} }
/// <summary> /// <summary>
/// Обработка нажатия кнопки "Шаг" /// Обработка нажатия кнопки "Шаг"
/// </summary> /// </summary>
@ -108,6 +113,7 @@ public partial class FormAccordionBus : Form
{ {
return; return;
} }
if (comboBoxStrategy.Enabled) if (comboBoxStrategy.Enabled)
{ {
_strategy = comboBoxStrategy.SelectedIndex switch _strategy = comboBoxStrategy.SelectedIndex switch
@ -120,21 +126,22 @@ public partial class FormAccordionBus : Form
{ {
return; return;
} }
_strategy.SetData(new MoveableBus(_drawningBus), _strategy.SetData(new MoveableBus(_drawningBus), pictureBoxAccordionBus.Width, pictureBoxAccordionBus.Height);
pictureBoxAccordionBus.Width, pictureBoxAccordionBus.Height);
} }
if (_strategy == null) if (_strategy == null)
{ {
return; return;
} }
comboBoxStrategy.Enabled = false; comboBoxStrategy.Enabled = false;
_strategy.MakeStep(); _strategy.MakeStep();
Draw(); Draw();
if (_strategy.GetStatus() == StrategyStatus.Finish) if (_strategy.GetStatus() == StrategyStatus.Finish)
{ {
comboBoxStrategy.Enabled = true; comboBoxStrategy.Enabled = true;
_strategy = null; _strategy = null;
} }
} }
} }

View File

@ -128,7 +128,7 @@
comboBoxSelectorCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; comboBoxSelectorCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList; comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true; comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" }); comboBoxSelectorCompany.Items.AddRange(new object[] { "Автовокзал" });
comboBoxSelectorCompany.Location = new Point(6, 22); comboBoxSelectorCompany.Location = new Point(6, 22);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany"; comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(170, 23); comboBoxSelectorCompany.Size = new Size(170, 23);

View File

@ -18,7 +18,7 @@ public partial class FormBusCollection : Form
/// <summary> /// <summary>
/// Компания /// Компания
/// </summary> /// </summary>
private AbstractCompany? _company = null; private AbstractBusStation? _company = null;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
@ -35,8 +35,8 @@ public partial class FormBusCollection : Form
{ {
switch (comboBoxSelectorCompany.Text) switch (comboBoxSelectorCompany.Text)
{ {
case "Хранилище": case "Автовокзал":
_company = new BusSharingService(pictureBox.Width, _company = new BusStation(pictureBox.Width,
pictureBox.Height, new MassiveGenericObjects<DrawningBus>()); pictureBox.Height, new MassiveGenericObjects<DrawningBus>());
break; break;
} }
@ -65,24 +65,18 @@ public partial class FormBusCollection : Form
} }
Random random = new(); Random random = new();
DrawningBus drawningBus; DrawningBus drawningBus;
Color bodyColor, additionalColor;
switch (type) switch (type)
{ {
case nameof(DrawningBus): case nameof(DrawningBus):
bodyColor = GetColor(random); drawningBus = new DrawningBus(random.Next(100, 300), random.Next(1000, 3000), GetColor(random));
drawningBus = new DrawningAccordionBus(random.Next(100, 300), random.Next(1000, 3000), bodyColor);
break; break;
case nameof(DrawningAccordionBus): case nameof(DrawningAccordionBus):
drawningBus = new DrawningBus(random.Next(100, 300),random.Next(1000, 3000), GetColor(random)); drawningBus = new DrawningAccordionBus(random.Next(100, 300),random.Next(1000, 3000),GetColor(random),GetColor(random), Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)));
bodyColor = GetColor(random);
additionalColor = GetColor(random);
drawningBus = new DrawningAccordionBus(random.Next(100,
300), random.Next(1000, 3000), bodyColor, additionalColor, Convert.ToBoolean(random.Next(0,2)), Convert.ToBoolean(random.Next(0, 2)));
break; break;
default: default:
return; return;
} }
if (_company + drawningBus) if (_company + drawningBus==1)
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();
@ -124,7 +118,7 @@ public partial class FormBusCollection : Form
return; return;
} }
int pos = Convert.ToInt32(maskedTextBoxPosition.Text); int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_company - pos) if (_company - pos!=null)
{ {
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show(); pictureBox.Image = _company.Show();