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

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;
/// <summary>
/// Абстракция компании, хранящий коллекцию автомобилей
/// Абстракция компании, хранящий коллекцию автобусов
/// </summary>
public abstract class AbstractCompany
public abstract class AbstractBusStation
{
/// <summary>
/// Размер места (ширина)
/// </summary>
protected readonly int _placeSizeWidth = 180;
protected readonly int _placeSizeWidth = 215;
/// <summary>
/// Размер места (высота)
/// </summary>
protected readonly int _placeSizeHeight = 40;
protected readonly int _placeSizeHeight = 50;
/// <summary>
/// Ширина окна
/// </summary>
@ -36,16 +36,14 @@ public abstract class AbstractCompany
/// <summary>
/// Вычисление максимального количества элементов, который можно разместить в окне
/// </summary>
private int GetMaxCount => _pictureWidth * _pictureHeight /
(_placeSizeWidth * _placeSizeHeight);
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<DrawningBus> collection)
public AbstractBusStation(int picWidth, int picHeight, ICollectionGenericObjects<DrawningBus> collection)
{
_pictureWidth = picWidth;
_pictureHeight = picHeight;
@ -58,9 +56,9 @@ private int GetMaxCount => _pictureWidth * _pictureHeight /
/// <param name="company">Компания</param>
/// <param name="car">Добавляемый объект</param>
/// <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>
/// Перегрузка оператора удаления для класса
@ -68,9 +66,9 @@ private int GetMaxCount => _pictureWidth * _pictureHeight /
/// <param name="company">Компания</param>
/// <param name="position">Номер удаляемого объекта</param>
/// <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>
/// Получение случайного объекта из коллекции

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="position">Позиция</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
bool Insert(T obj, int position);
bool? Insert(T obj, int position);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
/// </summary>
/// <param name="position">Позиция</param>
/// <returns>true - удаление прошло удачно, false - удаление не удалось</returns>
bool Remove(int position);
T? Remove(int position);
/// <summary>
/// Получение объекта по позиции
/// </summary>

View File

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

View File

@ -32,7 +32,7 @@ public class DrawningAccordionBus:DrawningBus
/// <param name="speed">скорость</param>
/// <param name="weight">вес</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);
}

View File

@ -27,12 +27,10 @@
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormAccordionBus));
pictureBoxAccordionBus = new PictureBox();
buttonCreate = new Button();
buttonUp = new Button();
buttonLeft = new Button();
buttonDown = new Button();
buttonRight = new Button();
buttonCreateBus = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxAccordionBus).BeginInit();
@ -48,16 +46,6 @@
pictureBoxAccordionBus.TabIndex = 5;
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.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
@ -110,16 +98,6 @@
buttonRight.UseVisualStyleBackColor = true;
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.Anchor = AnchorStyles.Top | AnchorStyles.Right;
@ -149,12 +127,10 @@
ClientSize = new Size(800, 450);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateBus);
Controls.Add(buttonRight);
Controls.Add(buttonDown);
Controls.Add(buttonLeft);
Controls.Add(buttonUp);
Controls.Add(buttonCreate);
Controls.Add(pictureBoxAccordionBus);
Name = "FormAccordionBus";
Text = "Автобус с гармошкой";
@ -164,12 +140,10 @@
}
#endregion
private PictureBox pictureBoxAccordionBus;
private Button buttonCreate;
private Button buttonUp;
private Button buttonLeft;
private Button buttonDown;
private Button buttonRight;
private Button buttonCreateBus;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
}

View File

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

View File

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

View File

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