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(); buttonRefreshCollection = new Button();
buttonRemoveShip = new Button(); buttonRemoveShip = new Button();
ButtonAddShip = 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(); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
groupBox1.SuspendLayout(); groupBox1.SuspendLayout();
groupBox2.SuspendLayout();
SuspendLayout(); SuspendLayout();
// //
// pictureBoxCollection // pictureBoxCollection
@ -63,14 +69,14 @@
// //
// maskedTextBoxNumber // maskedTextBoxNumber
// //
maskedTextBoxNumber.Location = new Point(16, 175); maskedTextBoxNumber.Location = new Point(16, 357);
maskedTextBoxNumber.Name = "maskedTextBoxNumber"; maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(136, 23); maskedTextBoxNumber.Size = new Size(136, 23);
maskedTextBoxNumber.TabIndex = 3; maskedTextBoxNumber.TabIndex = 3;
// //
// buttonRefreshCollection // buttonRefreshCollection
// //
buttonRefreshCollection.Location = new Point(16, 305); buttonRefreshCollection.Location = new Point(16, 415);
buttonRefreshCollection.Name = "buttonRefreshCollection"; buttonRefreshCollection.Name = "buttonRefreshCollection";
buttonRefreshCollection.Size = new Size(136, 23); buttonRefreshCollection.Size = new Size(136, 23);
buttonRefreshCollection.TabIndex = 2; buttonRefreshCollection.TabIndex = 2;
@ -80,7 +86,7 @@
// //
// buttonRemoveShip // buttonRemoveShip
// //
buttonRemoveShip.Location = new Point(16, 214); buttonRemoveShip.Location = new Point(16, 386);
buttonRemoveShip.Name = "buttonRemoveShip"; buttonRemoveShip.Name = "buttonRemoveShip";
buttonRemoveShip.Size = new Size(136, 23); buttonRemoveShip.Size = new Size(136, 23);
buttonRemoveShip.TabIndex = 1; buttonRemoveShip.TabIndex = 1;
@ -90,7 +96,7 @@
// //
// ButtonAddShip // ButtonAddShip
// //
ButtonAddShip.Location = new Point(16, 39); ButtonAddShip.Location = new Point(16, 328);
ButtonAddShip.Name = "ButtonAddShip"; ButtonAddShip.Name = "ButtonAddShip";
ButtonAddShip.Size = new Size(136, 23); ButtonAddShip.Size = new Size(136, 23);
ButtonAddShip.TabIndex = 0; ButtonAddShip.TabIndex = 0;
@ -98,11 +104,62 @@
ButtonAddShip.UseVisualStyleBackColor = true; ButtonAddShip.UseVisualStyleBackColor = true;
ButtonAddShip.Click += ButtonAddShip_Click; 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 // FormShipCollection
// //
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, 450);
Controls.Add(groupBox2);
Controls.Add(groupBox1); Controls.Add(groupBox1);
Controls.Add(pictureBoxCollection); Controls.Add(pictureBoxCollection);
Name = "FormShipCollection"; Name = "FormShipCollection";
@ -110,6 +167,8 @@
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
groupBox1.ResumeLayout(false); groupBox1.ResumeLayout(false);
groupBox1.PerformLayout(); groupBox1.PerformLayout();
groupBox2.ResumeLayout(false);
groupBox2.PerformLayout();
ResumeLayout(false); ResumeLayout(false);
PerformLayout(); PerformLayout();
} }
@ -122,5 +181,10 @@
private Button buttonRemoveShip; private Button buttonRemoveShip;
private Button ButtonAddShip; private Button ButtonAddShip;
private MaskedTextBox maskedTextBoxNumber; 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 namespace ProjectWarmlyShip
{ {
/// <summary> /// <summary>
/// Форма для работы с набором объектов класса DrawningCar /// Форма для работы с набором объектов класса DrawningShip
/// </summary> /// </summary>
public partial class FormShipCollection : Form public partial class FormShipCollection : Form
{ { /// <summary>
/// <summary> /// Набор объектов
/// Набор объектов /// </summary>
/// </summary> private readonly ShipsGenericStorage _storage;
private readonly ShipsGenericCollection<DrawningShip, DrawningObjectShip> _ships;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public FormShipCollection() public FormShipCollection()
{ {
InitializeComponent(); 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> /// <summary>
/// Добавление объекта в набор /// Добавление объекта в набор
@ -38,13 +103,23 @@ namespace ProjectWarmlyShip
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonAddShip_Click(object sender, EventArgs e) 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(); FormWarmlyShip form = new FormWarmlyShip();
if (form.ShowDialog() == DialogResult.OK) if (form.ShowDialog() == DialogResult.OK)
{ {
if (_ships + form.SelectedShip != -1) if (obj + form.SelectedShip)
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = _ships.ShowShips(); pictureBoxCollection.Image = obj.ShowShips();
} }
else else
{ {
@ -59,21 +134,26 @@ namespace ProjectWarmlyShip
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonRemoveShip_Click(object sender, EventArgs e) private void ButtonRemoveShip_Click(object sender, EventArgs e)
{ {
if (MessageBox.Show("Удалить объект?", "Удаление", if (listBoxStorages.SelectedIndex == -1)
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{ {
return; return;
} }
int pos = -1; var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
try string.Empty];
if (obj == null)
{ {
pos = Convert.ToInt32(maskedTextBoxNumber.Text); return;
} }
catch (Exception ex) { } if (MessageBox.Show("Удалить объект?", "Удаление",
if (_ships - pos) MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos != null)
{ {
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
pictureBoxCollection.Image = _ships.ShowShips(); pictureBoxCollection.Image = obj.ShowShips();
} }
else else
{ {
@ -87,8 +167,17 @@ namespace ProjectWarmlyShip
/// <param name="e"></param> /// <param name="e"></param>
private void ButtonRefreshCollection_Click(object sender, EventArgs e) 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;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Numerics;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace ProjectWarmlyShip.Generics namespace ProjectWarmlyShip.Generics
{/// <summary> {
/// Параметризованный набор объектов /// <summary>
/// </summary> /// Параметризованный набор объектов
/// <typeparam name="T"></typeparam> /// </summary>
/// <typeparam name="T"></typeparam>
internal class SetGeneric<T> internal class SetGeneric<T>
where T : class where T : class
{ {
/// <summary> /// <summary>
/// Массив объектов, которые храним /// Массив объектов, которые храним
/// </summary> /// </summary>
private readonly T?[] _places; private readonly List<T?> _places;
/// <summary> /// <summary>
/// Количество объектов в массиве /// Количество объектов в массиве
/// </summary> /// </summary>
public int Count => _places.Length; public int Count => _places.Count;
/// <summary>
/// Максимальное количество объектов в списке
/// </summary>
private readonly int _maxCount;
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
/// <param name="count"></param> /// <param name="count"></param>
public SetGeneric(int count) public SetGeneric(int count)
{ {
_places = new T?[count]; _maxCount = count;
_places = new List<T?>(count);
} }
/// <summary> /// <summary>
/// Добавление объекта в набор /// Добавление объекта в набор
/// </summary> /// </summary>
/// <param name="ship">Добавляемый корабль</param> /// <param name="ship">Добавляемый корабль</param>
/// <returns></returns> /// <returns></returns>
public int Insert(T ship) public bool Insert(T ship)
{ {
int index = -1; return Insert(ship, 0);
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;
} }
/// <summary> /// <summary>
/// Добавление объекта в набор на конкретную позицию /// Добавление объекта в набор на конкретную позицию
@ -60,31 +50,16 @@ namespace ProjectWarmlyShip.Generics
/// <param name="ship">Добавляемый корабль</param> /// <param name="ship">Добавляемый корабль</param>
/// <param name="position">Позиция</param> /// <param name="position">Позиция</param>
/// <returns></returns> /// <returns></returns>
public int Insert(T plane, int position) public bool Insert(T ship, int position)
{ {
if (position < 0 || position >= Count) if (position < 0 || position >= _maxCount)
return -1; return false;
if (_places[position] == null)
{ if (Count >= _maxCount)
_places[position] = plane; return false;
return position; _places.Insert(0, ship);
} return true;
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;
} }
/// <summary> /// <summary>
/// Удаление объекта из набора с конкретной позиции /// Удаление объекта из набора с конкретной позиции
@ -93,23 +68,48 @@ namespace ProjectWarmlyShip.Generics
/// <returns></returns> /// <returns></returns>
public bool Remove(int position) public bool Remove(int position)
{ {
if (position < 0 || position >= _places.Length) if (position < 0 || position > _maxCount)
return false; return false;
_places[position] = null; if (position >= Count)
return false;
_places.RemoveAt(position);
return true; return true;
} }
/// <summary> /// <summary>
/// Получение объекта из набора по позиции /// Получение объекта из набора по позиции
/// </summary> /// </summary>
/// <param name="position"></param> /// <param name="position"></param>
/// <returns></returns> /// <returns></returns>
public T? Get(int position) public T? this[int position]
{ {
if (position < 0 || position >= _places.Length) get
return null; {
if (position < 0 || position > _maxCount)
return _places[position]; 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="collect"></param>
/// <param name="obj"></param> /// <param name="obj"></param>
/// <returns></returns> /// <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) if (obj == null)
{ {
return -1; return false;
} }
return collect?._collection.Insert(obj); return (bool)collect?._collection.Insert(obj);
} }
/// <summary> /// <summary>
/// Перегрузка оператора вычитания /// Перегрузка оператора вычитания
@ -70,15 +70,14 @@ namespace ProjectWarmlyShip.Generics
/// <param name="collect"></param> /// <param name="collect"></param>
/// <param name="pos"></param> /// <param name="pos"></param>
/// <returns></returns> /// <returns></returns>
public static bool operator -(ShipsGenericCollection<T, U> collect, int public static T? operator -(ShipsGenericCollection<T, U> collect, int pos)
pos)
{ {
T? obj = collect._collection.Get(pos); T? obj = collect._collection[pos];
if (obj == null) if (obj != null)
{ {
return false; collect._collection.Remove(pos);
} }
return collect._collection.Remove(pos); return obj;
} }
/// <summary> /// <summary>
/// Получение объекта IMoveableObject /// Получение объекта IMoveableObject
@ -87,7 +86,7 @@ namespace ProjectWarmlyShip.Generics
/// <returns></returns> /// <returns></returns>
public U? GetU(int pos) public U? GetU(int pos)
{ {
return (U?)_collection.Get(pos)?.GetMoveableObject; return (U?)_collection[pos]?.GetMoveableObject;
} }
/// <summary> /// <summary>
/// Вывод всего набора объектов /// Вывод всего набора объектов
@ -132,7 +131,7 @@ namespace ProjectWarmlyShip.Generics
for (int i = 0; i < _collection.Count; i++) for (int i = 0; i < _collection.Count; i++)
{ {
// TODO получение объекта // TODO получение объекта
DrawningShip? Ship = _collection.Get(i); DrawningShip? Ship = _collection[i];
if (Ship == null) if (Ship == null)
continue; continue;
int r = i / width; 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;
}
}
}
}