4 базовая лабораторная

This commit is contained in:
kagbie3nn@mail.ru 2023-11-19 16:41:27 +04:00
parent dea0c71159
commit 398534d097
5 changed files with 326 additions and 94 deletions

View File

@ -34,8 +34,14 @@
buttonRefreshCollection = new Button();
buttonRemoveShip = new Button();
ButtonAddShip = new Button();
groupBox2 = new GroupBox();
buttonDelObject = new Button();
listBoxStorages = new ListBox();
buttonAddObject = new Button();
textBoxStorageName = new TextBox();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
groupBox1.SuspendLayout();
groupBox2.SuspendLayout();
SuspendLayout();
//
// pictureBoxCollection
@ -63,14 +69,14 @@
//
// maskedTextBoxNumber
//
maskedTextBoxNumber.Location = new Point(16, 175);
maskedTextBoxNumber.Location = new Point(16, 357);
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(136, 23);
maskedTextBoxNumber.TabIndex = 3;
//
// buttonRefreshCollection
//
buttonRefreshCollection.Location = new Point(16, 305);
buttonRefreshCollection.Location = new Point(16, 415);
buttonRefreshCollection.Name = "buttonRefreshCollection";
buttonRefreshCollection.Size = new Size(136, 23);
buttonRefreshCollection.TabIndex = 2;
@ -80,7 +86,7 @@
//
// buttonRemoveShip
//
buttonRemoveShip.Location = new Point(16, 214);
buttonRemoveShip.Location = new Point(16, 386);
buttonRemoveShip.Name = "buttonRemoveShip";
buttonRemoveShip.Size = new Size(136, 23);
buttonRemoveShip.TabIndex = 1;
@ -90,7 +96,7 @@
//
// ButtonAddShip
//
ButtonAddShip.Location = new Point(16, 39);
ButtonAddShip.Location = new Point(16, 328);
ButtonAddShip.Name = "ButtonAddShip";
ButtonAddShip.Size = new Size(136, 23);
ButtonAddShip.TabIndex = 0;
@ -98,11 +104,62 @@
ButtonAddShip.UseVisualStyleBackColor = true;
ButtonAddShip.Click += ButtonAddShip_Click;
//
// groupBox2
//
groupBox2.Controls.Add(buttonDelObject);
groupBox2.Controls.Add(listBoxStorages);
groupBox2.Controls.Add(buttonAddObject);
groupBox2.Controls.Add(textBoxStorageName);
groupBox2.Location = new Point(625, 22);
groupBox2.Name = "groupBox2";
groupBox2.Size = new Size(175, 300);
groupBox2.TabIndex = 4;
groupBox2.TabStop = false;
groupBox2.Text = "Наборы";
//
// buttonDelObject
//
buttonDelObject.Location = new Point(16, 240);
buttonDelObject.Name = "buttonDelObject";
buttonDelObject.Size = new Size(136, 23);
buttonDelObject.TabIndex = 3;
buttonDelObject.Text = "Удалить набор";
buttonDelObject.UseVisualStyleBackColor = true;
buttonDelObject.Click += ButtonDelObject_Click;
//
// listBoxStorages
//
listBoxStorages.FormattingEnabled = true;
listBoxStorages.ItemHeight = 15;
listBoxStorages.Location = new Point(16, 113);
listBoxStorages.Name = "listBoxStorages";
listBoxStorages.Size = new Size(136, 94);
listBoxStorages.TabIndex = 2;
listBoxStorages.Click += ListBoxObjects_SelectedIndexChanged;
//
// buttonAddObject
//
buttonAddObject.Location = new Point(16, 74);
buttonAddObject.Name = "buttonAddObject";
buttonAddObject.Size = new Size(136, 23);
buttonAddObject.TabIndex = 1;
buttonAddObject.Text = "Добавить набор";
buttonAddObject.UseVisualStyleBackColor = true;
buttonAddObject.Click += ButtonAddObject_Click;
//
// textBoxStorageName
//
textBoxStorageName.Location = new Point(16, 31);
textBoxStorageName.Name = "textBoxStorageName";
textBoxStorageName.Size = new Size(136, 23);
textBoxStorageName.TabIndex = 0;
//
// FormShipCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(groupBox2);
Controls.Add(groupBox1);
Controls.Add(pictureBoxCollection);
Name = "FormShipCollection";
@ -110,6 +167,8 @@
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
groupBox1.ResumeLayout(false);
groupBox1.PerformLayout();
groupBox2.ResumeLayout(false);
groupBox2.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
@ -122,5 +181,10 @@
private Button buttonRemoveShip;
private Button ButtonAddShip;
private MaskedTextBox maskedTextBoxNumber;
private GroupBox groupBox2;
private Button buttonDelObject;
private ListBox listBoxStorages;
private Button buttonAddObject;
private TextBox textBoxStorageName;
}
}

View File

@ -15,21 +15,86 @@ using System.Windows.Forms;
namespace ProjectWarmlyShip
{
/// <summary>
/// Форма для работы с набором объектов класса DrawningCar
/// Форма для работы с набором объектов класса DrawningShip
/// </summary>
public partial class FormShipCollection : Form
{
/// <summary>
/// Набор объектов
/// </summary>
private readonly ShipsGenericCollection<DrawningShip, DrawningObjectShip> _ships;
{ /// <summary>
/// Набор объектов
/// </summary>
private readonly ShipsGenericStorage _storage;
/// <summary>
/// Конструктор
/// </summary>
public FormShipCollection()
{
InitializeComponent();
_ships = new ShipsGenericCollection<DrawningShip, DrawningObjectShip>(pictureBoxCollection.Width, pictureBoxCollection.Height);
_storage = new ShipsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
}
/// <summary>
/// Заполнение listBoxObjects
/// </summary>
private void ReloadObjects()
{
int index = listBoxStorages.SelectedIndex;
listBoxStorages.Items.Clear();
foreach (var key in _storage.Keys)
{
listBoxStorages.Items.Add(key);
}
if (listBoxStorages.Items.Count > 0 && (index == -1 || index
>= listBoxStorages.Items.Count))
{
listBoxStorages.SelectedIndex = 0;
}
else if (listBoxStorages.Items.Count > 0 && index > -1 &&
index < listBoxStorages.Items.Count)
{
listBoxStorages.SelectedIndex = index;
}
}
/// <summary>
/// Добавление набора в коллекцию
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddObject_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxStorageName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
}
/// <summary>
/// Выбор набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ListBoxObjects_SelectedIndexChanged(object sender,
EventArgs e)
{
pictureBoxCollection.Image =
_storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowShips();
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonDelObject_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
if (MessageBox.Show($"Удалить объект{listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(listBoxStorages.SelectedItem.ToString()
?? string.Empty);
ReloadObjects();
}
}
/// <summary>
/// Добавление объекта в набор
@ -38,13 +103,23 @@ namespace ProjectWarmlyShip
/// <param name="e"></param>
private void ButtonAddShip_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
FormWarmlyShip form = new FormWarmlyShip();
if (form.ShowDialog() == DialogResult.OK)
{
if (_ships + form.SelectedShip != -1)
if (obj + form.SelectedShip)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = _ships.ShowShips();
pictureBoxCollection.Image = obj.ShowShips();
}
else
{
@ -59,21 +134,26 @@ namespace ProjectWarmlyShip
/// <param name="e"></param>
private void ButtonRemoveShip_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
int pos = -1;
try
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
pos = Convert.ToInt32(maskedTextBoxNumber.Text);
return;
}
catch (Exception ex) { }
if (_ships - pos)
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos != null)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = _ships.ShowShips();
pictureBoxCollection.Image = obj.ShowShips();
}
else
{
@ -87,8 +167,17 @@ namespace ProjectWarmlyShip
/// <param name="e"></param>
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
{
pictureBoxCollection.Image = _ships.ShowShips();
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
pictureBoxCollection.Image = obj.ShowShips();
}
}
}

View File

@ -1,58 +1,48 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
namespace ProjectWarmlyShip.Generics
{/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T"></typeparam>
{
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T"></typeparam>
internal class SetGeneric<T>
where T : class
where T : class
{
/// <summary>
/// Массив объектов, которые храним
/// </summary>
private readonly T?[] _places;
private readonly List<T?> _places;
/// <summary>
/// Количество объектов в массиве
/// </summary>
public int Count => _places.Length;
public int Count => _places.Count;
/// <summary>
/// Максимальное количество объектов в списке
/// </summary>
private readonly int _maxCount;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetGeneric(int count)
{
_places = new T?[count];
_maxCount = count;
_places = new List<T?>(count);
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="ship">Добавляемый корабль</param>
/// <returns></returns>
public int Insert(T ship)
public bool Insert(T ship)
{
int index = -1;
for (int i = 0; i < _places.Length; i++)
{
if (_places[i] == null)
{
index = i; break;
}
}
if (index < 0)
{
return -1;
}
for (int i = index; i > 0; i--)
{
_places[i] = _places[i - 1];
}
_places[0] = ship;
return 0;
return Insert(ship, 0);
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
@ -60,31 +50,16 @@ namespace ProjectWarmlyShip.Generics
/// <param name="ship">Добавляемый корабль</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public int Insert(T plane, int position)
public bool Insert(T ship, int position)
{
if (position < 0 || position >= Count)
return -1;
if (_places[position] == null)
{
_places[position] = plane;
return position;
}
int index = -1;
for (int i = position; i < Count; i++)
{
if (_places[i] == null)
{
index = i; break;
}
}
if (index < 0)
return -1;
for (int i = index; index > position; i--)
{
_places[i] = _places[i - 1];
}
_places[position] = plane;
return position;
if (position < 0 || position >= _maxCount)
return false;
if (Count >= _maxCount)
return false;
_places.Insert(0, ship);
return true;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
@ -93,23 +68,48 @@ namespace ProjectWarmlyShip.Generics
/// <returns></returns>
public bool Remove(int position)
{
if (position < 0 || position >= _places.Length)
if (position < 0 || position > _maxCount)
return false;
_places[position] = null;
if (position >= Count)
return false;
_places.RemoveAt(position);
return true;
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T? Get(int position)
public T? this[int position]
{
if (position < 0 || position >= _places.Length)
return null;
return _places[position];
get
{
if (position < 0 || position > _maxCount)
return null;
return _places[position];
}
set
{
if (position < 0 || position > _maxCount)
return;
_places[position] = value;
}
}
/// <summary>
/// Проход по списку
/// </summary>
/// <returns></returns>
public IEnumerable<T?> GetShips(int? maxShips = null)
{
for (int i = 0; i < _places.Count; ++i)
{
yield return _places[i];
if (maxShips.HasValue && i == maxShips.Value)
{
yield break;
}
}
}
}
}
}

View File

@ -56,13 +56,13 @@ namespace ProjectWarmlyShip.Generics
/// <param name="collect"></param>
/// <param name="obj"></param>
/// <returns></returns>
public static int? operator +(ShipsGenericCollection<T, U> collect, T? obj)
public static bool operator +(ShipsGenericCollection<T, U> collect, T? obj)
{
if (obj == null)
{
return -1;
return false;
}
return collect?._collection.Insert(obj);
return (bool)collect?._collection.Insert(obj);
}
/// <summary>
/// Перегрузка оператора вычитания
@ -70,15 +70,14 @@ namespace ProjectWarmlyShip.Generics
/// <param name="collect"></param>
/// <param name="pos"></param>
/// <returns></returns>
public static bool operator -(ShipsGenericCollection<T, U> collect, int
pos)
public static T? operator -(ShipsGenericCollection<T, U> collect, int pos)
{
T? obj = collect._collection.Get(pos);
if (obj == null)
T? obj = collect._collection[pos];
if (obj != null)
{
return false;
collect._collection.Remove(pos);
}
return collect._collection.Remove(pos);
return obj;
}
/// <summary>
/// Получение объекта IMoveableObject
@ -87,7 +86,7 @@ namespace ProjectWarmlyShip.Generics
/// <returns></returns>
public U? GetU(int pos)
{
return (U?)_collection.Get(pos)?.GetMoveableObject;
return (U?)_collection[pos]?.GetMoveableObject;
}
/// <summary>
/// Вывод всего набора объектов
@ -132,7 +131,7 @@ namespace ProjectWarmlyShip.Generics
for (int i = 0; i < _collection.Count; i++)
{
// TODO получение объекта
DrawningShip? Ship = _collection.Get(i);
DrawningShip? Ship = _collection[i];
if (Ship == null)
continue;
int r = i / width;

View File

@ -0,0 +1,80 @@
using ProjectWarmlyShip.DrawningObjects;
using ProjectWarmlyShip.Generics;
using ProjectWarmlyShip.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectWarmlyShip
{
/// <summary>
/// Класс для хранения коллекции
/// </summary>
internal class ShipsGenericStorage
{
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<string, ShipsGenericCollection<DrawningShip, DrawningObjectShip>> _shipStorages;
/// <summary>
/// Возвращение списка названий наборов
/// </summary>
public List<string> Keys => _shipStorages.Keys.ToList();
/// <summary>
/// Ширина окна отрисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна отрисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="pictureWidth"></param>
/// /// <param name="pictureHeight"></param>
public ShipsGenericStorage(int pictureWidth, int pictureHeight)
{
_shipStorages = new Dictionary<string, ShipsGenericCollection<DrawningShip, DrawningObjectShip>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
/// <summary>
/// Добавление набора
/// </summary>
/// <param name="name">Название набора</param>
public void AddSet(string name)
{
// TODO Прописать логику для добавления
if (_shipStorages.ContainsKey(name)) return;
_shipStorages[name] = new ShipsGenericCollection<DrawningShip, DrawningObjectShip>(_pictureWidth, _pictureHeight);
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="name">Название набора</param>
public void DelSet(string name)
{
// TODO Прописать логику для удаления
if (!_shipStorages.ContainsKey(name)) return;
_shipStorages.Remove(name);
}
/// <summary>
/// Доступ к набору
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public ShipsGenericCollection<DrawningShip, DrawningObjectShip>?
this[string ind]
{
get
{
// TODO Продумать логику получения набора
if (_shipStorages.ContainsKey(ind)) return _shipStorages[ind];
return null;
}
}
}
}