Замена массива на список и добавление нового класса

This commit is contained in:
Максим Егоров 2024-01-15 22:44:26 +03:00
parent 1e10a3cb96
commit 375e66b131
6 changed files with 312 additions and 117 deletions

View File

@ -56,14 +56,13 @@ namespace Sailboat.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 +(BoatsGenericCollection<T, U> collect, T? public static bool operator +(BoatsGenericCollection<T, U> collect, T? obj)
obj)
{ {
if (obj == null) if (obj == null)
{ {
return -1; return false;
} }
return collect._collection.Insert(obj); return (bool)collect?._collection.Insert(obj);
} }
/// <summary> /// <summary>
/// Перегрузка оператора вычитания /// Перегрузка оператора вычитания
@ -71,16 +70,16 @@ namespace Sailboat.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 -(BoatsGenericCollection<T, U> collect, int public static bool operator -(BoatsGenericCollection<T, U> collect, int pos)
pos)
{ {
T? obj = collect._collection.Get(pos); T? obj = collect._collection[pos];
if (obj != null) if (obj != null)
{ {
collect._collection.Remove(pos); collect._collection.Remove(pos);
} }
return false; return false;
} }
/// <summary> /// <summary>
/// Получение объекта IMoveableObject /// Получение объекта IMoveableObject
/// </summary> /// </summary>
@ -88,7 +87,7 @@ namespace Sailboat.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>
/// Вывод всего набора объектов /// Вывод всего набора объектов
@ -128,18 +127,17 @@ namespace Sailboat.Generics
/// <param name="g"></param> /// <param name="g"></param>
private void DrawObjects(Graphics g) private void DrawObjects(Graphics g)
{ {
for (int i = 0; i < _collection.Count; i++) int i = 0;
foreach (var boat in _collection.GetBoats())
{ {
DrawingBoat boat = _collection.Get(i);
if (boat != null) if (boat != null)
{ {
int width = _pictureWidth / _placeSizeWidth; int width = _pictureWidth / _placeSizeWidth;
boat.SetPosition(i % width * _placeSizeWidth, i / width * _placeSizeHeight); boat.SetPosition(i % width * _placeSizeWidth, i / width * _placeSizeHeight);
boat.DrawTransport(g); boat.DrawTransport(g);
} }
i++;
} }
} }
} }
} }

View File

@ -0,0 +1,84 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sailboat.DrawingObjects;
using Sailboat.MovementStrategy;
namespace Sailboat.Generics
{
internal class BoatsGenericStorage
{
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<string, BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>> _boatStorages;
/// <summary>
/// Возвращение списка названий наборов
/// </summary>
public List<string> Keys => _boatStorages.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 BoatsGenericStorage(int pictureWidth, int pictureHeight)
{
_boatStorages = new Dictionary<string,
BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
/// <summary>
/// Добавление набора
/// </summary>
/// <param name="name">Название набора</param>
public void AddSet(string name)
{
if (_boatStorages.ContainsKey(name))
{
return;
}
_boatStorages[name] = new BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>(_pictureWidth, _pictureHeight);
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="name">Название набора</param>
public void DelSet(string name)
{
if (!_boatStorages.ContainsKey(name))
{
return;
}
_boatStorages.Remove(name);
}
/// <summary>
/// Доступ к набору
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>?
this[string ind]
{
get
{
if (_boatStorages.ContainsKey(ind))
{
return _boatStorages[ind];
}
return null;
}
}
}
}

View File

@ -28,89 +28,96 @@
/// </summary> /// </summary>
private void InitializeComponent() private void InitializeComponent()
{ {
this.pictureBoxCollection = new System.Windows.Forms.PictureBox(); pictureBoxCollection = new PictureBox();
this.panelTools = new System.Windows.Forms.Panel(); panelTools = new Panel();
this.maskedTextBoxNumber = new System.Windows.Forms.MaskedTextBox(); maskedTextBoxNumber = new MaskedTextBox();
this.buttonRefreshCollection = new System.Windows.Forms.Button(); buttonRefreshCollection = new Button();
this.buttonRemoveBoat = new System.Windows.Forms.Button(); buttonRemoveBoat = new Button();
this.buttonAddBoat = new System.Windows.Forms.Button(); buttonAddBoat = new Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
this.panelTools.SuspendLayout(); panelTools.SuspendLayout();
this.SuspendLayout(); SuspendLayout();
// //
// pictureBoxCollection // pictureBoxCollection
// //
this.pictureBoxCollection.Location = new System.Drawing.Point(0, 0); pictureBoxCollection.Location = new Point(0, 0);
this.pictureBoxCollection.Name = "pictureBoxCollection"; pictureBoxCollection.Margin = new Padding(3, 2, 3, 2);
this.pictureBoxCollection.Size = new System.Drawing.Size(750, 450); pictureBoxCollection.Name = "pictureBoxCollection";
this.pictureBoxCollection.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; pictureBoxCollection.Size = new Size(750, 450);
this.pictureBoxCollection.TabIndex = 0; pictureBoxCollection.SizeMode = PictureBoxSizeMode.AutoSize;
this.pictureBoxCollection.TabStop = false; pictureBoxCollection.TabIndex = 0;
pictureBoxCollection.TabStop = false;
pictureBoxCollection.Click += pictureBoxCollection_Click;
// //
// panelTools // panelTools
// //
this.panelTools.BackColor = System.Drawing.SystemColors.ScrollBar; panelTools.BackColor = SystemColors.ScrollBar;
this.panelTools.Controls.Add(this.maskedTextBoxNumber); panelTools.Controls.Add(maskedTextBoxNumber);
this.panelTools.Controls.Add(this.buttonRefreshCollection); panelTools.Controls.Add(buttonRefreshCollection);
this.panelTools.Controls.Add(this.buttonRemoveBoat); panelTools.Controls.Add(buttonRemoveBoat);
this.panelTools.Controls.Add(this.buttonAddBoat); panelTools.Controls.Add(buttonAddBoat);
this.panelTools.Location = new System.Drawing.Point(756, 12); panelTools.Location = new Point(662, 9);
this.panelTools.Name = "panelTools"; panelTools.Margin = new Padding(3, 2, 3, 2);
this.panelTools.Size = new System.Drawing.Size(209, 426); panelTools.Name = "panelTools";
this.panelTools.TabIndex = 1; panelTools.Size = new Size(183, 320);
panelTools.TabIndex = 1;
// //
// maskedTextBoxNumber // maskedTextBoxNumber
// //
this.maskedTextBoxNumber.Location = new System.Drawing.Point(40, 87); maskedTextBoxNumber.Location = new Point(35, 65);
this.maskedTextBoxNumber.Name = "maskedTextBoxNumber"; maskedTextBoxNumber.Margin = new Padding(3, 2, 3, 2);
this.maskedTextBoxNumber.Size = new System.Drawing.Size(125, 27); maskedTextBoxNumber.Name = "maskedTextBoxNumber";
this.maskedTextBoxNumber.TabIndex = 3; maskedTextBoxNumber.Size = new Size(110, 23);
maskedTextBoxNumber.TabIndex = 3;
// //
// buttonRefreshCollection // buttonRefreshCollection
// //
this.buttonRefreshCollection.Location = new System.Drawing.Point(16, 210); buttonRefreshCollection.Location = new Point(14, 158);
this.buttonRefreshCollection.Name = "buttonRefreshCollection"; buttonRefreshCollection.Margin = new Padding(3, 2, 3, 2);
this.buttonRefreshCollection.Size = new System.Drawing.Size(180, 34); buttonRefreshCollection.Name = "buttonRefreshCollection";
this.buttonRefreshCollection.TabIndex = 2; buttonRefreshCollection.Size = new Size(158, 26);
this.buttonRefreshCollection.Text = "Обновить коллекцию"; buttonRefreshCollection.TabIndex = 2;
this.buttonRefreshCollection.UseVisualStyleBackColor = true; buttonRefreshCollection.Text = "Обновить коллекцию";
this.buttonRefreshCollection.Click += new System.EventHandler(this.buttonRefreshCollection_Click); buttonRefreshCollection.UseVisualStyleBackColor = true;
buttonRefreshCollection.Click += buttonRefreshCollection_Click;
// //
// buttonRemoveBoat // buttonRemoveBoat
// //
this.buttonRemoveBoat.Location = new System.Drawing.Point(16, 159); buttonRemoveBoat.Location = new Point(14, 119);
this.buttonRemoveBoat.Name = "buttonRemoveBoat"; buttonRemoveBoat.Margin = new Padding(3, 2, 3, 2);
this.buttonRemoveBoat.Size = new System.Drawing.Size(180, 34); buttonRemoveBoat.Name = "buttonRemoveBoat";
this.buttonRemoveBoat.TabIndex = 1; buttonRemoveBoat.Size = new Size(158, 26);
this.buttonRemoveBoat.Text = "Удалить лодку"; buttonRemoveBoat.TabIndex = 1;
this.buttonRemoveBoat.UseVisualStyleBackColor = true; buttonRemoveBoat.Text = "Удалить лодку";
this.buttonRemoveBoat.Click += new System.EventHandler(this.buttonRemoveBoat_Click); buttonRemoveBoat.UseVisualStyleBackColor = true;
buttonRemoveBoat.Click += buttonRemoveBoat_Click;
// //
// buttonAddBoat // buttonAddBoat
// //
this.buttonAddBoat.Location = new System.Drawing.Point(16, 14); buttonAddBoat.Location = new Point(14, 10);
this.buttonAddBoat.Name = "buttonAddBoat"; buttonAddBoat.Margin = new Padding(3, 2, 3, 2);
this.buttonAddBoat.Size = new System.Drawing.Size(180, 34); buttonAddBoat.Name = "buttonAddBoat";
this.buttonAddBoat.TabIndex = 0; buttonAddBoat.Size = new Size(158, 26);
this.buttonAddBoat.Text = "Добавить лодку"; buttonAddBoat.TabIndex = 0;
this.buttonAddBoat.UseVisualStyleBackColor = true; buttonAddBoat.Text = "Добавить лодку";
this.buttonAddBoat.Click += new System.EventHandler(this.buttonAddBoat_Click); buttonAddBoat.UseVisualStyleBackColor = true;
buttonAddBoat.Click += buttonAddBoat_Click;
// //
// FormBoatCollection // FormBoatCollection
// //
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); AutoScaleDimensions = new SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(969, 450); ClientSize = new Size(848, 338);
this.Controls.Add(this.panelTools); Controls.Add(pictureBoxCollection);
this.Controls.Add(this.pictureBoxCollection); Controls.Add(panelTools);
this.Name = "FormBoatCollection"; Margin = new Padding(3, 2, 3, 2);
this.Text = "FormBoatCollection"; Name = "FormBoatCollection";
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).EndInit(); Text = "FormBoatCollection";
this.panelTools.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
this.panelTools.PerformLayout(); panelTools.ResumeLayout(false);
this.ResumeLayout(false); panelTools.PerformLayout();
this.PerformLayout(); ResumeLayout(false);
PerformLayout();
} }
#endregion #endregion

View File

@ -57,12 +57,16 @@ namespace Sailboat
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не удалось удалить объект");
pictureBoxCollection.Image = _boats.ShowBoats(); pictureBoxCollection.Image = _boats.ShowBoats();
} }
} }
private void buttonRefreshCollection_Click(object sender, EventArgs e) private void buttonRefreshCollection_Click(object sender, EventArgs e)
{ {
pictureBoxCollection.Image = _boats.ShowBoats(); pictureBoxCollection.Image = _boats.ShowBoats();
} }
private void pictureBoxCollection_Click(object sender, EventArgs e)
{
}
} }
} }

View File

@ -1,4 +1,64 @@
<root> <?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" /> <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true"> <xsd:element name="root" msdata:IsDataSet="true">

View File

@ -8,64 +8,106 @@ namespace Sailboat.Generics
{ {
internal class SetGeneric<T> where T : class internal class SetGeneric<T> where T : class
{ {
private readonly T?[] _places; /// <summary>
public int Count => _places.Length; /// Список объектов, которые храним
/// </summary>
private readonly List <T?> _places;
/// <summary>
/// Количество объектов в массиве
/// </summary>
public int Count => _places.Count;
/// <summary>
/// Максимальное количество объектов в списке
/// </summary>
private readonly int _maxCount;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetGeneric(int count) public SetGeneric(int count)
{ {
_places = new T?[count]; _maxCount = count;
_places = new List<T?>(count);
} }
public int Insert(T boat) /// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="boat">Добавляемая лодка</param>
/// <returns></returns>
public bool Insert(T boat)
{ {
return Insert(boat, 0); if (_places.Count == _maxCount)
{
return false;
}
Insert(boat, 0);
return true;
} }
public int Insert(T boat, int position) /// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="boat">Добавляемая лодка</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public bool Insert(T boat, int position)
{ {
int nullIndex = -1, i; if (!(position >= 0 && position <= Count && _places.Count < _maxCount)) {
return false;
if (position < 0 || position >= Count)
{
return -1;
} }
_places.Insert(position, boat);
for (i = position; i < Count; i++) return true;
{
if (_places[i] == null)
{
nullIndex = i;
break;
}
}
if (nullIndex < 0)
{
return -1;
}
for (i = nullIndex; i > position; i--)
{
_places[i] = _places[i - 1];
}
_places[position] = boat;
return position;
} }
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public bool Remove(int position) public bool Remove(int position)
{ {
if (position < 0 || position >= Count) if (position < 0 || position >= Count)
{ {
return false; return false;
} }
_places.RemoveAt(position);
_places[position] = null;
return true; return true;
} }
public T? Get(int position) /// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T? this[int position]
{ {
if (position < 0 || position >= Count) get
{ {
return null; if (position < 0 || position >= Count) {
return null;
}
return _places[position];
}
set
{
if (!(position >= 0 && position < Count && _places.Count < _maxCount)) {
return;
}
_places.Insert(position, value);
return;
}
}
/// <summary>
/// Проход по списку
/// </summary>
/// <returns></returns>
public IEnumerable<T?> GetBoats(int? maxBoats = null)
{
for (int i = 0; i < _places.Count; ++i)
{
yield return _places[i];
if (maxBoats.HasValue && i == maxBoats.Value)
{
yield break;
}
} }
return _places[position];
} }
} }
} }