Лабораторная работа 4

This commit is contained in:
Efi 2023-04-01 02:04:47 +04:00
parent 7cb730e265
commit c1f6009f6e
5 changed files with 294 additions and 141 deletions

View File

@ -40,8 +40,14 @@
buttonDown = new Button(); buttonDown = new Button();
buttonRight = new Button(); buttonRight = new Button();
groupBoxTools = new GroupBox(); groupBoxTools = new GroupBox();
groupBoxMaps = new GroupBox();
textBoxNewMapName = new TextBox();
buttonDeleteMap = new Button();
buttonAddMap = new Button();
listBoxMaps = new ListBox();
((System.ComponentModel.ISupportInitialize)pictureBoxLocomotive).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxLocomotive).BeginInit();
groupBoxTools.SuspendLayout(); groupBoxTools.SuspendLayout();
groupBoxMaps.SuspendLayout();
SuspendLayout(); SuspendLayout();
// //
// pictureBoxLocomotive // pictureBoxLocomotive
@ -49,7 +55,7 @@
pictureBoxLocomotive.Dock = DockStyle.Left; pictureBoxLocomotive.Dock = DockStyle.Left;
pictureBoxLocomotive.Location = new Point(0, 0); pictureBoxLocomotive.Location = new Point(0, 0);
pictureBoxLocomotive.Name = "pictureBoxLocomotive"; pictureBoxLocomotive.Name = "pictureBoxLocomotive";
pictureBoxLocomotive.Size = new Size(579, 450); pictureBoxLocomotive.Size = new Size(579, 561);
pictureBoxLocomotive.TabIndex = 0; pictureBoxLocomotive.TabIndex = 0;
pictureBoxLocomotive.TabStop = false; pictureBoxLocomotive.TabStop = false;
// //
@ -58,17 +64,16 @@
comboBoxSelectorMap.DropDownStyle = ComboBoxStyle.DropDownList; comboBoxSelectorMap.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorMap.FormattingEnabled = true; comboBoxSelectorMap.FormattingEnabled = true;
comboBoxSelectorMap.Items.AddRange(new object[] { "Простая карта", "Карта с грязью", "Карта с кустами" }); comboBoxSelectorMap.Items.AddRange(new object[] { "Простая карта", "Карта с грязью", "Карта с кустами" });
comboBoxSelectorMap.Location = new Point(26, 22); comboBoxSelectorMap.Location = new Point(15, 53);
comboBoxSelectorMap.Name = "comboBoxSelectorMap"; comboBoxSelectorMap.Name = "comboBoxSelectorMap";
comboBoxSelectorMap.Size = new Size(168, 23); comboBoxSelectorMap.Size = new Size(168, 23);
comboBoxSelectorMap.TabIndex = 2; comboBoxSelectorMap.TabIndex = 2;
comboBoxSelectorMap.SelectedIndexChanged += ComboBoxSelectorMap_SelectedIndexChanged;
// //
// buttonAddCar // buttonAddCar
// //
buttonAddCar.Location = new Point(26, 70); buttonAddCar.Location = new Point(23, 288);
buttonAddCar.Name = "buttonAddCar"; buttonAddCar.Name = "buttonAddCar";
buttonAddCar.Size = new Size(168, 28); buttonAddCar.Size = new Size(169, 30);
buttonAddCar.TabIndex = 3; buttonAddCar.TabIndex = 3;
buttonAddCar.Text = "Добавить локомотив"; buttonAddCar.Text = "Добавить локомотив";
buttonAddCar.UseVisualStyleBackColor = true; buttonAddCar.UseVisualStyleBackColor = true;
@ -76,7 +81,7 @@
// //
// buttonRemoveCar // buttonRemoveCar
// //
buttonRemoveCar.Location = new Point(26, 151); buttonRemoveCar.Location = new Point(23, 353);
buttonRemoveCar.Name = "buttonRemoveCar"; buttonRemoveCar.Name = "buttonRemoveCar";
buttonRemoveCar.Size = new Size(169, 30); buttonRemoveCar.Size = new Size(169, 30);
buttonRemoveCar.TabIndex = 4; buttonRemoveCar.TabIndex = 4;
@ -86,9 +91,9 @@
// //
// buttonShowStorage // buttonShowStorage
// //
buttonShowStorage.Location = new Point(26, 222); buttonShowStorage.Location = new Point(25, 406);
buttonShowStorage.Name = "buttonShowStorage"; buttonShowStorage.Name = "buttonShowStorage";
buttonShowStorage.Size = new Size(168, 39); buttonShowStorage.Size = new Size(169, 30);
buttonShowStorage.TabIndex = 5; buttonShowStorage.TabIndex = 5;
buttonShowStorage.Text = "Посмотреть хранилище"; buttonShowStorage.Text = "Посмотреть хранилище";
buttonShowStorage.UseVisualStyleBackColor = true; buttonShowStorage.UseVisualStyleBackColor = true;
@ -96,9 +101,9 @@
// //
// buttonShowOnMap // buttonShowOnMap
// //
buttonShowOnMap.Location = new Point(26, 307); buttonShowOnMap.Location = new Point(25, 443);
buttonShowOnMap.Name = "buttonShowOnMap"; buttonShowOnMap.Name = "buttonShowOnMap";
buttonShowOnMap.Size = new Size(169, 34); buttonShowOnMap.Size = new Size(169, 30);
buttonShowOnMap.TabIndex = 6; buttonShowOnMap.TabIndex = 6;
buttonShowOnMap.Text = "Посмотреть карту"; buttonShowOnMap.Text = "Посмотреть карту";
buttonShowOnMap.UseVisualStyleBackColor = true; buttonShowOnMap.UseVisualStyleBackColor = true;
@ -106,16 +111,16 @@
// //
// maskedTextBoxPosition // maskedTextBoxPosition
// //
maskedTextBoxPosition.Location = new Point(26, 193); maskedTextBoxPosition.Location = new Point(24, 324);
maskedTextBoxPosition.Name = "maskedTextBoxPosition"; maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(168, 23); maskedTextBoxPosition.Size = new Size(169, 23);
maskedTextBoxPosition.TabIndex = 7; maskedTextBoxPosition.TabIndex = 7;
// //
// buttonUp // buttonUp
// //
buttonUp.BackgroundImage = Properties.Resources.arrowUp; buttonUp.BackgroundImage = Properties.Resources.arrowUp;
buttonUp.BackgroundImageLayout = ImageLayout.Zoom; buttonUp.BackgroundImageLayout = ImageLayout.Zoom;
buttonUp.Location = new Point(98, 366); buttonUp.Location = new Point(96, 483);
buttonUp.Name = "buttonUp"; buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(30, 30); buttonUp.Size = new Size(30, 30);
buttonUp.TabIndex = 8; buttonUp.TabIndex = 8;
@ -126,7 +131,7 @@
// //
buttonLeft.BackgroundImage = Properties.Resources.arrowLeft; buttonLeft.BackgroundImage = Properties.Resources.arrowLeft;
buttonLeft.BackgroundImageLayout = ImageLayout.Zoom; buttonLeft.BackgroundImageLayout = ImageLayout.Zoom;
buttonLeft.Location = new Point(62, 402); buttonLeft.Location = new Point(60, 519);
buttonLeft.Name = "buttonLeft"; buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(30, 30); buttonLeft.Size = new Size(30, 30);
buttonLeft.TabIndex = 9; buttonLeft.TabIndex = 9;
@ -137,7 +142,7 @@
// //
buttonDown.BackgroundImage = Properties.Resources.arrowDown; buttonDown.BackgroundImage = Properties.Resources.arrowDown;
buttonDown.BackgroundImageLayout = ImageLayout.Zoom; buttonDown.BackgroundImageLayout = ImageLayout.Zoom;
buttonDown.Location = new Point(98, 402); buttonDown.Location = new Point(96, 519);
buttonDown.Name = "buttonDown"; buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(30, 30); buttonDown.Size = new Size(30, 30);
buttonDown.TabIndex = 10; buttonDown.TabIndex = 10;
@ -148,7 +153,7 @@
// //
buttonRight.BackgroundImage = Properties.Resources.arrowRight; buttonRight.BackgroundImage = Properties.Resources.arrowRight;
buttonRight.BackgroundImageLayout = ImageLayout.Zoom; buttonRight.BackgroundImageLayout = ImageLayout.Zoom;
buttonRight.Location = new Point(134, 402); buttonRight.Location = new Point(132, 519);
buttonRight.Name = "buttonRight"; buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(30, 30); buttonRight.Size = new Size(30, 30);
buttonRight.TabIndex = 11; buttonRight.TabIndex = 11;
@ -158,6 +163,7 @@
// groupBoxTools // groupBoxTools
// //
groupBoxTools.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; groupBoxTools.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
groupBoxTools.Controls.Add(groupBoxMaps);
groupBoxTools.Controls.Add(buttonRight); groupBoxTools.Controls.Add(buttonRight);
groupBoxTools.Controls.Add(buttonDown); groupBoxTools.Controls.Add(buttonDown);
groupBoxTools.Controls.Add(buttonLeft); groupBoxTools.Controls.Add(buttonLeft);
@ -167,19 +173,69 @@
groupBoxTools.Controls.Add(buttonShowStorage); groupBoxTools.Controls.Add(buttonShowStorage);
groupBoxTools.Controls.Add(buttonRemoveCar); groupBoxTools.Controls.Add(buttonRemoveCar);
groupBoxTools.Controls.Add(buttonAddCar); groupBoxTools.Controls.Add(buttonAddCar);
groupBoxTools.Controls.Add(comboBoxSelectorMap); groupBoxTools.Location = new Point(585, 0);
groupBoxTools.Location = new Point(585, -2);
groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(212, 451); groupBoxTools.Size = new Size(212, 560);
groupBoxTools.TabIndex = 12; groupBoxTools.TabIndex = 12;
groupBoxTools.TabStop = false; groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты"; groupBoxTools.Text = "Инструменты";
// //
// groupBoxMaps
//
groupBoxMaps.Controls.Add(textBoxNewMapName);
groupBoxMaps.Controls.Add(buttonDeleteMap);
groupBoxMaps.Controls.Add(buttonAddMap);
groupBoxMaps.Controls.Add(listBoxMaps);
groupBoxMaps.Controls.Add(comboBoxSelectorMap);
groupBoxMaps.Location = new Point(8, 21);
groupBoxMaps.Name = "groupBoxMaps";
groupBoxMaps.Size = new Size(197, 249);
groupBoxMaps.TabIndex = 16;
groupBoxMaps.TabStop = false;
groupBoxMaps.Text = "Карты";
//
// textBoxNewMapName
//
textBoxNewMapName.Location = new Point(14, 24);
textBoxNewMapName.Name = "textBoxNewMapName";
textBoxNewMapName.Size = new Size(169, 23);
textBoxNewMapName.TabIndex = 15;
//
// buttonDeleteMap
//
buttonDeleteMap.Location = new Point(15, 208);
buttonDeleteMap.Name = "buttonDeleteMap";
buttonDeleteMap.Size = new Size(169, 30);
buttonDeleteMap.TabIndex = 14;
buttonDeleteMap.Text = "Удалить карту";
buttonDeleteMap.UseVisualStyleBackColor = true;
buttonDeleteMap.Click += ButtonDeleteMap_Click;
//
// buttonAddMap
//
buttonAddMap.Location = new Point(15, 82);
buttonAddMap.Name = "buttonAddMap";
buttonAddMap.Size = new Size(169, 30);
buttonAddMap.TabIndex = 13;
buttonAddMap.Text = "Добавить карту";
buttonAddMap.UseVisualStyleBackColor = true;
buttonAddMap.Click += ButtonAddMap_Click;
//
// listBoxMaps
//
listBoxMaps.FormattingEnabled = true;
listBoxMaps.ItemHeight = 15;
listBoxMaps.Location = new Point(15, 123);
listBoxMaps.Name = "listBoxMaps";
listBoxMaps.Size = new Size(169, 79);
listBoxMaps.TabIndex = 12;
listBoxMaps.SelectedIndexChanged += listBoxMaps_SelectedIndexChanged;
//
// FormMapWithSetLocomotive // FormMapWithSetLocomotive
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450); ClientSize = new Size(800, 561);
Controls.Add(groupBoxTools); Controls.Add(groupBoxTools);
Controls.Add(pictureBoxLocomotive); Controls.Add(pictureBoxLocomotive);
Name = "FormMapWithSetLocomotive"; Name = "FormMapWithSetLocomotive";
@ -187,6 +243,8 @@
((System.ComponentModel.ISupportInitialize)pictureBoxLocomotive).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxLocomotive).EndInit();
groupBoxTools.ResumeLayout(false); groupBoxTools.ResumeLayout(false);
groupBoxTools.PerformLayout(); groupBoxTools.PerformLayout();
groupBoxMaps.ResumeLayout(false);
groupBoxMaps.PerformLayout();
ResumeLayout(false); ResumeLayout(false);
} }
@ -204,5 +262,10 @@
private Button buttonDown; private Button buttonDown;
private Button buttonRight; private Button buttonRight;
private GroupBox groupBoxTools; private GroupBox groupBoxTools;
private Button buttonDeleteMap;
private Button buttonAddMap;
private ListBox listBoxMaps;
private GroupBox groupBoxMaps;
private TextBox textBoxNewMapName;
} }
} }

View File

@ -12,50 +12,94 @@ namespace Monorail
{ {
public partial class FormMapWithSetLocomotive : Form public partial class FormMapWithSetLocomotive : Form
{ {
private MapWithSetLocomotiveGeneric <DrawingObjectLocomotive, AbstractMap> _mapLocomotivesCollectionGeneric; private readonly Dictionary<string, AbstractMap> _mapsDict = new()
{
{ "Простая карта", new SimpleMap() },
{ "Карта с грязью", new FieldMap() },
{ "Карта с кустами", new BushesMap() }
};
private readonly MapsCollection _mapsCollection;
public FormMapWithSetLocomotive() public FormMapWithSetLocomotive()
{ {
InitializeComponent(); InitializeComponent();
} _mapsCollection = new MapsCollection(pictureBoxLocomotive.Width, pictureBoxLocomotive.Height);
private void ComboBoxSelectorMap_SelectedIndexChanged(object sender, comboBoxSelectorMap.Items.Clear();
EventArgs e) foreach (var elem in _mapsDict)
{ {
AbstractMap map = null; comboBoxSelectorMap.Items.Add(elem.Key);
switch (comboBoxSelectorMap.Text) }
}
private void ReloadMaps()
{ {
case "Простая карта": int index = listBoxMaps.SelectedIndex;
map = new SimpleMap();
break; listBoxMaps.Items.Clear();
case "Карта с грязью": for (int i = 0; i < _mapsCollection.Keys.Count; i++)
map = new FieldMap();
break;
case "Карта с кустами":
map = new BushesMap();
break;
}
if (map != null)
{ {
_mapLocomotivesCollectionGeneric = new MapWithSetLocomotiveGeneric<DrawingObjectLocomotive, AbstractMap>(pictureBoxLocomotive.Width, pictureBoxLocomotive.Height, map); listBoxMaps.Items.Add(_mapsCollection.Keys[i]);
} }
else
if (listBoxMaps.Items.Count > 0 && (index == -1 || index >= listBoxMaps.Items.Count))
{ {
_mapLocomotivesCollectionGeneric = null; listBoxMaps.SelectedIndex = 0;
}
else if (listBoxMaps.Items.Count > 0 && index > -1 && index < listBoxMaps.Items.Count)
{
listBoxMaps.SelectedIndex = index;
} }
} }
private void ButtonAddMap_Click(object sender, EventArgs e)
{
if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text))
{
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps();
}
private void listBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBoxLocomotive.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
private void ButtonDeleteMap_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps();
}
}
private void ButtonAddLocomotive_Click(object sender, EventArgs e) private void ButtonAddLocomotive_Click(object sender, EventArgs e)
{ {
if (_mapLocomotivesCollectionGeneric == null) if (listBoxMaps.SelectedIndex == -1)
{ {
return; return;
} }
FormLocomotive form = new(); FormLocomotive form = new();
if (form.ShowDialog() == DialogResult.OK) if (form.ShowDialog() == DialogResult.OK)
{ {
DrawingObjectLocomotive Locomotive = new(form.SelectedLocomotive); DrawingObjectLocomotive locomotive = new(form.SelectedLocomotive);
if (_mapLocomotivesCollectionGeneric + Locomotive != -1) if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + locomotive >= 0)
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBoxLocomotive.Image = _mapLocomotivesCollectionGeneric.ShowSet(); pictureBoxLocomotive.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
} }
else else
{ {
@ -63,51 +107,57 @@ namespace Monorail
} }
} }
} }
private void ButtonRemoveLocomotive_Click(object sender, EventArgs e) private void ButtonRemoveLocomotive_Click(object sender, EventArgs e)
{ {
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text)) if (string.IsNullOrEmpty(maskedTextBoxPosition.Text))
{ {
return; return;
} }
if (MessageBox.Show("Удалить объект?", "Удаление", if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{ {
return; return;
} }
int pos = Convert.ToInt32(maskedTextBoxPosition.Text); int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_mapLocomotivesCollectionGeneric - pos != null) if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
{ {
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
pictureBoxLocomotive.Image = _mapLocomotivesCollectionGeneric.ShowSet(); pictureBoxLocomotive.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
} }
else else
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не удалось удалить объект");
} }
} }
private void ButtonShowStorage_Click(object sender, EventArgs e) private void ButtonShowStorage_Click(object sender, EventArgs e)
{ {
if (_mapLocomotivesCollectionGeneric == null) if (listBoxMaps.SelectedIndex == -1)
{ {
return; return;
} }
pictureBoxLocomotive.Image = _mapLocomotivesCollectionGeneric.ShowSet(); pictureBoxLocomotive.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
} }
private void ButtonShowOnMap_Click(object sender, EventArgs e) private void ButtonShowOnMap_Click(object sender, EventArgs e)
{ {
if (_mapLocomotivesCollectionGeneric == null) if (listBoxMaps.SelectedIndex == -1)
{ {
return; return;
} }
pictureBoxLocomotive.Image = _mapLocomotivesCollectionGeneric.ShowOnMap(); pictureBoxLocomotive.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowOnMap();
} }
private void ButtonMove_Click(object sender, EventArgs e) private void ButtonMove_Click(object sender, EventArgs e)
{ {
if (_mapLocomotivesCollectionGeneric == null) if (listBoxMaps.SelectedIndex == -1)
{ {
return; return;
} }
//получаем имя кнопки
string name = ((Button)sender)?.Name ?? string.Empty; string name = ((Button)sender)?.Name ?? string.Empty;
Direction dir = Direction.None; Direction dir = Direction.None;
switch (name) switch (name)
@ -125,7 +175,7 @@ namespace Monorail
dir = Direction.Right; dir = Direction.Right;
break; break;
} }
pictureBoxLocomotive.Image = _mapLocomotivesCollectionGeneric.MoveObject(dir); pictureBoxLocomotive.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].MoveObject(dir);
} }
} }
} }

View File

@ -35,17 +35,15 @@ where T : class, IDrawingObject
_map = map; _map = map;
} }
// Перегрузка оператора сложения // Перегрузка оператора сложения
public static int operator +(MapWithSetLocomotiveGeneric<T, U> map, T Locomotive) public static int operator +(MapWithSetLocomotiveGeneric<T, U> map, T locomotive)
{ {
return map._setLocomotive.Insert(Locomotive); return map._setLocomotive.Insert(locomotive);
} }
// Перегрузка оператора вычитания
public static T operator -(MapWithSetLocomotiveGeneric<T, U> map, int position) public static T operator -(MapWithSetLocomotiveGeneric<T, U> map, int position)
{ {
return map._setLocomotive.Remove(position); return map._setLocomotive.Remove(position);
} }
// Вывод всего набора объектов
public Bitmap ShowSet() public Bitmap ShowSet()
{ {
Bitmap bmp = new(_pictureWidth, _pictureHeight); Bitmap bmp = new(_pictureWidth, _pictureHeight);
@ -54,21 +52,16 @@ where T : class, IDrawingObject
DrawLocomotive(gr); DrawLocomotive(gr);
return bmp; return bmp;
} }
// Просмотр объекта на карте
public Bitmap ShowOnMap() public Bitmap ShowOnMap()
{ {
Shaking(); Shaking();
for (int i = 0; i < _setLocomotive.Count; i++) foreach (var locomotive in _setLocomotive.GetLocomotives())
{ {
var Locomotive = _setLocomotive.Get(i); return _map.CreateMap(_pictureWidth, _pictureHeight, locomotive);
if (Locomotive != null)
{
return _map.CreateMap(_pictureWidth, _pictureHeight, Locomotive);
}
} }
return new(_pictureWidth, _pictureHeight); return new(_pictureWidth, _pictureHeight);
} }
// Перемещение объекта по карте
public Bitmap MoveObject(Direction direction) public Bitmap MoveObject(Direction direction)
{ {
if (_map != null) if (_map != null)
@ -77,17 +70,17 @@ where T : class, IDrawingObject
} }
return new(_pictureWidth, _pictureHeight); return new(_pictureWidth, _pictureHeight);
} }
// "Взбалтываем" набор, чтобы все элементы оказались в начале
private void Shaking() private void Shaking()
{ {
int j = _setLocomotive.Count - 1; int j = _setLocomotive.Count - 1;
for (int i = 0; i < _setLocomotive.Count; i++) for (int i = 0; i < _setLocomotive.Count; i++)
{ {
if (_setLocomotive.Get(i) == null) if (_setLocomotive[i] == null)
{ {
for (; j > i; j--) for (; j > i; j--)
{ {
var Locomotive = _setLocomotive.Get(j); var Locomotive = _setLocomotive[j];
if (Locomotive != null) if (Locomotive != null)
{ {
_setLocomotive.Insert(Locomotive, i); _setLocomotive.Insert(Locomotive, i);
@ -102,6 +95,7 @@ where T : class, IDrawingObject
} }
} }
} }
// Метод отрисовки фона // Метод отрисовки фона
private void DrawBackground(Graphics g) private void DrawBackground(Graphics g)
{ {
@ -124,10 +118,10 @@ where T : class, IDrawingObject
int xPosition = _pictureWidth - _placeSizeWidth; int xPosition = _pictureWidth - _placeSizeWidth;
int yPosition = 12; int yPosition = 12;
for (int i = 0; i < _setLocomotive.Count; i++) foreach (var locomotive in _setLocomotive.GetLocomotives())
{ {
_setLocomotive.Get(i)?.SetObject(xPosition, yPosition, _pictureWidth, _pictureHeight); locomotive.SetObject(xPosition, yPosition, _pictureWidth, _pictureHeight);
_setLocomotive.Get(i)?.DrawingObject(g); locomotive.DrawingObject(g);
xPosition -= _placeSizeWidth; xPosition -= _placeSizeWidth;
if (xPosition < 0) if (xPosition < 0)

View File

@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Monorail
{
internal class MapsCollection
{
readonly Dictionary<string, MapWithSetLocomotiveGeneric<DrawingObjectLocomotive, AbstractMap>> _mapStorages;
public List<string> Keys => _mapStorages.Keys.ToList();
private readonly int _pictureWidth;
private readonly int _pictureHeight;
public MapsCollection(int pictureWidth, int pictureHeight)
{
_mapStorages = new Dictionary<string, MapWithSetLocomotiveGeneric<DrawingObjectLocomotive, AbstractMap>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
public void AddMap(string name, AbstractMap map)
{
if (!_mapStorages.ContainsKey(name))
{
_mapStorages.Add(name, new MapWithSetLocomotiveGeneric<DrawingObjectLocomotive, AbstractMap>
(_pictureWidth, _pictureHeight, map));
}
}
public void DelMap(string name)
{
if (_mapStorages.ContainsKey(name))
_mapStorages.Remove(name);
}
public MapWithSetLocomotiveGeneric<DrawingObjectLocomotive, AbstractMap> this[string ind]
{
get
{
if (_mapStorages.ContainsKey(ind))
return _mapStorages[ind];
else
return null;
}
}
}
}

View File

@ -9,72 +9,69 @@ namespace Monorail
internal class SetLocomotiveGeneric<T> internal class SetLocomotiveGeneric<T>
where T : class where T : class
{ {
// Массив объектов, которые храним private readonly List<T> _places;
private readonly T[] _places; public int Count => _places.Count;
// Количество объектов в массиве private readonly int _maxCount;
public int Count => _places.Length;
// Конструктор
public SetLocomotiveGeneric(int count) public SetLocomotiveGeneric(int count)
{ {
_places = new T[count]; _maxCount = count;
_places = new List<T>();
} }
// Добавление объекта в набор
public int Insert(T Locomotive) public int Insert(T locomotive)
{ {
// вставка в начало набора return Insert(locomotive, 0);
return Insert(Locomotive, 0);
} }
// Добавление объекта в набор на конкретную позицию public int Insert(T locomotive, int position)
public int Insert(T Locomotive, int position)
{ {
// проверка позиции if (position <= _places.Count && _places.Count < _maxCount && position >= 0)
if (position >= _places.Length || position < 0) {
_places.Insert(position, locomotive);
return position;
}
else
return -1; return -1;
//проверка, что элемент массива по этой позиции пустой, если нет, то
if (_places[position] == null)
{
_places[position] = Locomotive;
return position;
} }
//проверка, что после вставляемого элемента в массиве есть пустой элемент
int findEmptyPos = -1;
for (int i = position + 1; i < Count; i++)
{
if (_places[i] == null)
{
findEmptyPos = i;
break;
}
}
if (findEmptyPos < 0) return -1;
//сдвиг всех объектов, находящихся справа от позиции до первого пустого элемента
for (int i = findEmptyPos; i > position; i--)
{
_places[i] = _places[i - 1];
}
// вставка по позиции
_places[position] = Locomotive;
return position;
}
// Удаление объекта из набора с конкретной позиции
public T Remove(int position) public T Remove(int position)
{ {
// проверка позиции if (position < _places.Count && position >= 0)
if (position >= _places.Length || position < 0) return null;
// удаление объекта из массива, присовив элементу массива значение null
T temp = _places[position];
_places[position] = null;
return temp;
}
// Получение объекта из набора по позиции
public T Get(int position)
{ {
// проверка позиции var locomotive = _places[position];
if (position >= _places.Length || position < 0) _places.RemoveAt(position);
return locomotive;
}
else
return null; return null;
}
public T this[int position]
{
get
{
if (position < _places.Count && position >= 0)
return _places[position]; return _places[position];
else
return null;
}
set
{
Insert(value, position);
}
}
public IEnumerable<T> GetLocomotives()
{
foreach (var locomotive in _places)
{
if (locomotive != null)
{
yield return locomotive;
}
else
{
yield break;
}
}
} }
} }
} }