Лабораторная работа 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();
buttonRight = new Button();
groupBoxTools = new GroupBox();
groupBoxMaps = new GroupBox();
textBoxNewMapName = new TextBox();
buttonDeleteMap = new Button();
buttonAddMap = new Button();
listBoxMaps = new ListBox();
((System.ComponentModel.ISupportInitialize)pictureBoxLocomotive).BeginInit();
groupBoxTools.SuspendLayout();
groupBoxMaps.SuspendLayout();
SuspendLayout();
//
// pictureBoxLocomotive
@ -49,7 +55,7 @@
pictureBoxLocomotive.Dock = DockStyle.Left;
pictureBoxLocomotive.Location = new Point(0, 0);
pictureBoxLocomotive.Name = "pictureBoxLocomotive";
pictureBoxLocomotive.Size = new Size(579, 450);
pictureBoxLocomotive.Size = new Size(579, 561);
pictureBoxLocomotive.TabIndex = 0;
pictureBoxLocomotive.TabStop = false;
//
@ -58,17 +64,16 @@
comboBoxSelectorMap.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorMap.FormattingEnabled = true;
comboBoxSelectorMap.Items.AddRange(new object[] { "Простая карта", "Карта с грязью", "Карта с кустами" });
comboBoxSelectorMap.Location = new Point(26, 22);
comboBoxSelectorMap.Location = new Point(15, 53);
comboBoxSelectorMap.Name = "comboBoxSelectorMap";
comboBoxSelectorMap.Size = new Size(168, 23);
comboBoxSelectorMap.TabIndex = 2;
comboBoxSelectorMap.SelectedIndexChanged += ComboBoxSelectorMap_SelectedIndexChanged;
//
// buttonAddCar
//
buttonAddCar.Location = new Point(26, 70);
buttonAddCar.Location = new Point(23, 288);
buttonAddCar.Name = "buttonAddCar";
buttonAddCar.Size = new Size(168, 28);
buttonAddCar.Size = new Size(169, 30);
buttonAddCar.TabIndex = 3;
buttonAddCar.Text = "Добавить локомотив";
buttonAddCar.UseVisualStyleBackColor = true;
@ -76,7 +81,7 @@
//
// buttonRemoveCar
//
buttonRemoveCar.Location = new Point(26, 151);
buttonRemoveCar.Location = new Point(23, 353);
buttonRemoveCar.Name = "buttonRemoveCar";
buttonRemoveCar.Size = new Size(169, 30);
buttonRemoveCar.TabIndex = 4;
@ -86,9 +91,9 @@
//
// buttonShowStorage
//
buttonShowStorage.Location = new Point(26, 222);
buttonShowStorage.Location = new Point(25, 406);
buttonShowStorage.Name = "buttonShowStorage";
buttonShowStorage.Size = new Size(168, 39);
buttonShowStorage.Size = new Size(169, 30);
buttonShowStorage.TabIndex = 5;
buttonShowStorage.Text = "Посмотреть хранилище";
buttonShowStorage.UseVisualStyleBackColor = true;
@ -96,9 +101,9 @@
//
// buttonShowOnMap
//
buttonShowOnMap.Location = new Point(26, 307);
buttonShowOnMap.Location = new Point(25, 443);
buttonShowOnMap.Name = "buttonShowOnMap";
buttonShowOnMap.Size = new Size(169, 34);
buttonShowOnMap.Size = new Size(169, 30);
buttonShowOnMap.TabIndex = 6;
buttonShowOnMap.Text = "Посмотреть карту";
buttonShowOnMap.UseVisualStyleBackColor = true;
@ -106,16 +111,16 @@
//
// maskedTextBoxPosition
//
maskedTextBoxPosition.Location = new Point(26, 193);
maskedTextBoxPosition.Location = new Point(24, 324);
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(168, 23);
maskedTextBoxPosition.Size = new Size(169, 23);
maskedTextBoxPosition.TabIndex = 7;
//
// buttonUp
//
buttonUp.BackgroundImage = Properties.Resources.arrowUp;
buttonUp.BackgroundImageLayout = ImageLayout.Zoom;
buttonUp.Location = new Point(98, 366);
buttonUp.Location = new Point(96, 483);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(30, 30);
buttonUp.TabIndex = 8;
@ -126,7 +131,7 @@
//
buttonLeft.BackgroundImage = Properties.Resources.arrowLeft;
buttonLeft.BackgroundImageLayout = ImageLayout.Zoom;
buttonLeft.Location = new Point(62, 402);
buttonLeft.Location = new Point(60, 519);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(30, 30);
buttonLeft.TabIndex = 9;
@ -137,7 +142,7 @@
//
buttonDown.BackgroundImage = Properties.Resources.arrowDown;
buttonDown.BackgroundImageLayout = ImageLayout.Zoom;
buttonDown.Location = new Point(98, 402);
buttonDown.Location = new Point(96, 519);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(30, 30);
buttonDown.TabIndex = 10;
@ -148,7 +153,7 @@
//
buttonRight.BackgroundImage = Properties.Resources.arrowRight;
buttonRight.BackgroundImageLayout = ImageLayout.Zoom;
buttonRight.Location = new Point(134, 402);
buttonRight.Location = new Point(132, 519);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(30, 30);
buttonRight.TabIndex = 11;
@ -158,6 +163,7 @@
// groupBoxTools
//
groupBoxTools.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
groupBoxTools.Controls.Add(groupBoxMaps);
groupBoxTools.Controls.Add(buttonRight);
groupBoxTools.Controls.Add(buttonDown);
groupBoxTools.Controls.Add(buttonLeft);
@ -167,19 +173,69 @@
groupBoxTools.Controls.Add(buttonShowStorage);
groupBoxTools.Controls.Add(buttonRemoveCar);
groupBoxTools.Controls.Add(buttonAddCar);
groupBoxTools.Controls.Add(comboBoxSelectorMap);
groupBoxTools.Location = new Point(585, -2);
groupBoxTools.Location = new Point(585, 0);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(212, 451);
groupBoxTools.Size = new Size(212, 560);
groupBoxTools.TabIndex = 12;
groupBoxTools.TabStop = false;
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
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
ClientSize = new Size(800, 561);
Controls.Add(groupBoxTools);
Controls.Add(pictureBoxLocomotive);
Name = "FormMapWithSetLocomotive";
@ -187,6 +243,8 @@
((System.ComponentModel.ISupportInitialize)pictureBoxLocomotive).EndInit();
groupBoxTools.ResumeLayout(false);
groupBoxTools.PerformLayout();
groupBoxMaps.ResumeLayout(false);
groupBoxMaps.PerformLayout();
ResumeLayout(false);
}
@ -204,5 +262,10 @@
private Button buttonDown;
private Button buttonRight;
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
{
private MapWithSetLocomotiveGeneric <DrawingObjectLocomotive, AbstractMap> _mapLocomotivesCollectionGeneric;
private readonly Dictionary<string, AbstractMap> _mapsDict = new()
{
{ "Простая карта", new SimpleMap() },
{ "Карта с грязью", new FieldMap() },
{ "Карта с кустами", new BushesMap() }
};
private readonly MapsCollection _mapsCollection;
public FormMapWithSetLocomotive()
{
InitializeComponent();
_mapsCollection = new MapsCollection(pictureBoxLocomotive.Width, pictureBoxLocomotive.Height);
comboBoxSelectorMap.Items.Clear();
foreach (var elem in _mapsDict)
{
comboBoxSelectorMap.Items.Add(elem.Key);
}
}
private void ComboBoxSelectorMap_SelectedIndexChanged(object sender,
EventArgs e)
private void ReloadMaps()
{
AbstractMap map = null;
switch (comboBoxSelectorMap.Text)
int index = listBoxMaps.SelectedIndex;
listBoxMaps.Items.Clear();
for (int i = 0; i < _mapsCollection.Keys.Count; i++)
{
case "Простая карта":
map = new SimpleMap();
break;
case "Карта с грязью":
map = new FieldMap();
break;
case "Карта с кустами":
map = new BushesMap();
break;
listBoxMaps.Items.Add(_mapsCollection.Keys[i]);
}
if (map != null)
if (listBoxMaps.Items.Count > 0 && (index == -1 || index >= listBoxMaps.Items.Count))
{
_mapLocomotivesCollectionGeneric = new MapWithSetLocomotiveGeneric<DrawingObjectLocomotive, AbstractMap>(pictureBoxLocomotive.Width, pictureBoxLocomotive.Height, map);
listBoxMaps.SelectedIndex = 0;
}
else
else if (listBoxMaps.Items.Count > 0 && index > -1 && index < listBoxMaps.Items.Count)
{
_mapLocomotivesCollectionGeneric = null;
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)
{
if (_mapLocomotivesCollectionGeneric == null)
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
FormLocomotive form = new();
if (form.ShowDialog() == DialogResult.OK)
{
DrawingObjectLocomotive Locomotive = new(form.SelectedLocomotive);
if (_mapLocomotivesCollectionGeneric + Locomotive != -1)
DrawingObjectLocomotive locomotive = new(form.SelectedLocomotive);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + locomotive >= 0)
{
MessageBox.Show("Объект добавлен");
pictureBoxLocomotive.Image = _mapLocomotivesCollectionGeneric.ShowSet();
pictureBoxLocomotive.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
@ -63,51 +107,57 @@ namespace Monorail
}
}
}
private void ButtonRemoveLocomotive_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text))
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_mapLocomotivesCollectionGeneric - pos != null)
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
{
MessageBox.Show("Объект удален");
pictureBoxLocomotive.Image = _mapLocomotivesCollectionGeneric.ShowSet();
pictureBoxLocomotive.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
private void ButtonShowStorage_Click(object sender, EventArgs e)
{
if (_mapLocomotivesCollectionGeneric == null)
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
pictureBoxLocomotive.Image = _mapLocomotivesCollectionGeneric.ShowSet();
pictureBoxLocomotive.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
private void ButtonShowOnMap_Click(object sender, EventArgs e)
{
if (_mapLocomotivesCollectionGeneric == null)
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
pictureBoxLocomotive.Image = _mapLocomotivesCollectionGeneric.ShowOnMap();
pictureBoxLocomotive.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowOnMap();
}
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_mapLocomotivesCollectionGeneric == null)
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
//получаем имя кнопки
string name = ((Button)sender)?.Name ?? string.Empty;
Direction dir = Direction.None;
switch (name)
@ -125,7 +175,7 @@ namespace Monorail
dir = Direction.Right;
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;
}
// Перегрузка оператора сложения
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)
{
return map._setLocomotive.Remove(position);
}
// Вывод всего набора объектов
public Bitmap ShowSet()
{
Bitmap bmp = new(_pictureWidth, _pictureHeight);
@ -54,21 +52,16 @@ where T : class, IDrawingObject
DrawLocomotive(gr);
return bmp;
}
// Просмотр объекта на карте
public Bitmap ShowOnMap()
{
Shaking();
for (int i = 0; i < _setLocomotive.Count; i++)
foreach (var locomotive in _setLocomotive.GetLocomotives())
{
var Locomotive = _setLocomotive.Get(i);
if (Locomotive != null)
{
return _map.CreateMap(_pictureWidth, _pictureHeight, Locomotive);
}
return _map.CreateMap(_pictureWidth, _pictureHeight, locomotive);
}
return new(_pictureWidth, _pictureHeight);
}
// Перемещение объекта по карте
public Bitmap MoveObject(Direction direction)
{
if (_map != null)
@ -77,17 +70,17 @@ where T : class, IDrawingObject
}
return new(_pictureWidth, _pictureHeight);
}
// "Взбалтываем" набор, чтобы все элементы оказались в начале
private void Shaking()
{
int j = _setLocomotive.Count - 1;
for (int i = 0; i < _setLocomotive.Count; i++)
{
if (_setLocomotive.Get(i) == null)
if (_setLocomotive[i] == null)
{
for (; j > i; j--)
{
var Locomotive = _setLocomotive.Get(j);
var Locomotive = _setLocomotive[j];
if (Locomotive != null)
{
_setLocomotive.Insert(Locomotive, i);
@ -102,6 +95,7 @@ where T : class, IDrawingObject
}
}
}
// Метод отрисовки фона
private void DrawBackground(Graphics g)
{
@ -124,10 +118,10 @@ where T : class, IDrawingObject
int xPosition = _pictureWidth - _placeSizeWidth;
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);
_setLocomotive.Get(i)?.DrawingObject(g);
locomotive.SetObject(xPosition, yPosition, _pictureWidth, _pictureHeight);
locomotive.DrawingObject(g);
xPosition -= _placeSizeWidth;
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

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