Готовая 3 лабораторная

This commit is contained in:
Даниил Путинцев 2023-10-10 22:08:33 +04:00
parent 852c7c8a50
commit 5d96a63aa7
9 changed files with 653 additions and 58 deletions

View File

@ -4,6 +4,7 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using RoadTrain.Entities; using RoadTrain.Entities;
using RoadTrain.MovementStrategy;
namespace RoadTrain.DrawningObjects namespace RoadTrain.DrawningObjects
{ {
@ -101,10 +102,6 @@ namespace RoadTrain.DrawningObjects
/// <param name="y">Координата Y</param> /// <param name="y">Координата Y</param>
public void SetPosition(int x, int y) public void SetPosition(int x, int y)
{ {
if (x < 0) { x = 0; }
if (y < 0) { y = 0; }
if (x > 200) { x = 200; }
if (y > 200) { y = 200; }
_startPosX = x; _startPosX = x;
_startPosY = y; _startPosY = y;
} }
@ -139,6 +136,9 @@ namespace RoadTrain.DrawningObjects
break; break;
} }
} }
public IMoveableObject GetMoveableObject => new
DrawningObjectTrain(this);
/// <summary> /// <summary>
/// Прорисовка объекта /// Прорисовка объекта
/// </summary> /// </summary>

View File

@ -33,10 +33,11 @@
buttonUp = new Button(); buttonUp = new Button();
buttonRight = new Button(); buttonRight = new Button();
buttonDown = new Button(); buttonDown = new Button();
buttonCreate = new Button();
button1 = new Button();
comboBoxStrategy = new ComboBox(); comboBoxStrategy = new ComboBox();
ButtonStep = new Button(); ButtonStep = new Button();
ButtonCreateTrain = new Button();
ButtonCreateRoadTrain = new Button();
ButtonSelectTrain = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxRoadTrain).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxRoadTrain).BeginInit();
SuspendLayout(); SuspendLayout();
// //
@ -96,27 +97,6 @@
buttonDown.UseVisualStyleBackColor = true; buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += ButtonMove_Click; buttonDown.Click += ButtonMove_Click;
// //
// buttonCreate
//
buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreate.Location = new Point(82, 236);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(107, 38);
buttonCreate.TabIndex = 6;
buttonCreate.Text = "создать грузовик";
buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += buttonCreate_Click;
//
// button1
//
button1.Location = new Point(82, 289);
button1.Name = "button1";
button1.Size = new Size(107, 55);
button1.TabIndex = 7;
button1.Text = "создать очистительную машину";
button1.UseVisualStyleBackColor = true;
button1.Click += button1_Click;
//
// comboBoxStrategy // comboBoxStrategy
// //
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList; comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
@ -137,15 +117,46 @@
ButtonStep.UseVisualStyleBackColor = true; ButtonStep.UseVisualStyleBackColor = true;
ButtonStep.Click += ButtonStep_Click_1; ButtonStep.Click += ButtonStep_Click_1;
// //
// ButtonCreateTrain
//
ButtonCreateTrain.Location = new Point(30, 285);
ButtonCreateTrain.Name = "ButtonCreateTrain";
ButtonCreateTrain.Size = new Size(115, 43);
ButtonCreateTrain.TabIndex = 11;
ButtonCreateTrain.Text = "Создать моющую машину";
ButtonCreateTrain.UseVisualStyleBackColor = true;
ButtonCreateTrain.Click += ButtonCreateTrain_Click;
//
// ButtonCreateRoadTrain
//
ButtonCreateRoadTrain.Location = new Point(180, 285);
ButtonCreateRoadTrain.Name = "ButtonCreateRoadTrain";
ButtonCreateRoadTrain.Size = new Size(93, 43);
ButtonCreateRoadTrain.TabIndex = 12;
ButtonCreateRoadTrain.Text = "Создать поезд";
ButtonCreateRoadTrain.UseVisualStyleBackColor = true;
ButtonCreateRoadTrain.Click += ButtonCreateRoadTrain_Click;
//
// ButtonSelectTrain
//
ButtonSelectTrain.Location = new Point(567, 94);
ButtonSelectTrain.Name = "ButtonSelectTrain";
ButtonSelectTrain.Size = new Size(89, 42);
ButtonSelectTrain.TabIndex = 13;
ButtonSelectTrain.Text = "Добавить поезд";
ButtonSelectTrain.UseVisualStyleBackColor = true;
ButtonSelectTrain.Click += ButtonSelectTrain_Click;
//
// FormRoadTrain // FormRoadTrain
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(679, 363); ClientSize = new Size(679, 363);
Controls.Add(ButtonSelectTrain);
Controls.Add(ButtonCreateRoadTrain);
Controls.Add(ButtonCreateTrain);
Controls.Add(ButtonStep); Controls.Add(ButtonStep);
Controls.Add(comboBoxStrategy); Controls.Add(comboBoxStrategy);
Controls.Add(button1);
Controls.Add(buttonCreate);
Controls.Add(buttonDown); Controls.Add(buttonDown);
Controls.Add(buttonRight); Controls.Add(buttonRight);
Controls.Add(buttonUp); Controls.Add(buttonUp);
@ -165,9 +176,10 @@
private Button buttonUp; private Button buttonUp;
private Button buttonRight; private Button buttonRight;
private Button buttonDown; private Button buttonDown;
private Button buttonCreate;
private Button button1;
private ComboBox comboBoxStrategy; private ComboBox comboBoxStrategy;
private Button ButtonStep; private Button ButtonStep;
private Button ButtonCreateTrain;
private Button ButtonCreateRoadTrain;
private Button ButtonSelectTrain;
} }
} }

View File

@ -1,5 +1,6 @@
using RoadTrain.MovementStrategy; using RoadTrain.MovementStrategy;
using RoadTrain.DrawningObjects; using RoadTrain.DrawningObjects;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Window;
namespace RoadTrain namespace RoadTrain
@ -12,12 +13,16 @@ namespace RoadTrain
private DrawningRoadTrain? _drawningRoadTrain; private DrawningRoadTrain? _drawningRoadTrain;
private AbstractStrategy? _abstractStrategy; private AbstractStrategy? _abstractStrategy;
public DrawningRoadTrain? SelectedTrain { get; private set; }
/// <summary> /// <summary>
/// Èíèöèàëèçàöèÿ ôîðìû /// Èíèöèàëèçàöèÿ ôîðìû
/// </summary> /// </summary>
public FormRoadTrain() public FormRoadTrain()
{ {
InitializeComponent(); InitializeComponent();
_abstractStrategy = null;
SelectedTrain = null;
} }
/// <summary> /// <summary>
/// Ìåòîä ïðîðèñîâêè ìàøèíû /// Ìåòîä ïðîðèñîâêè ìàøèíû
@ -70,33 +75,7 @@ namespace RoadTrain
Draw(); Draw();
} }
private void buttonCreate_Click(object sender, EventArgs e)
{
Random random = new();
_drawningRoadTrain = new DrawningRoadTrain(random.Next(100, 300), random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256),
random.Next(0, 256)),
pictureBoxRoadTrain.Width, pictureBoxRoadTrain.Height);
_drawningRoadTrain.SetPosition(random.Next(10, 100),
random.Next(10, 100));
Draw();
}
private void button1_Click(object sender, EventArgs e)
{
Random random = new();
_drawningRoadTrain = new DrawningTrain(random.Next(100, 300), random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256),
random.Next(0, 256)),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256),
random.Next(0, 256)),
Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)),
pictureBoxRoadTrain.Width, pictureBoxRoadTrain.Height);
_drawningRoadTrain.SetPosition(random.Next(10, 100),
random.Next(10, 100));
Draw();
}
private void ButtonStep_Click_1(object sender, EventArgs e) private void ButtonStep_Click_1(object sender, EventArgs e)
@ -135,5 +114,57 @@ namespace RoadTrain
_abstractStrategy = null; _abstractStrategy = null;
} }
} }
private void ButtonCreateRoadTrain_Click(object sender, EventArgs e)
{
Random random = new();
Color color = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
_drawningRoadTrain = new DrawningRoadTrain(random.Next(100, 300),
random.Next(1000, 3000), color,
pictureBoxRoadTrain.Width, pictureBoxRoadTrain.Height);
_drawningRoadTrain.SetPosition(random.Next(10, 100), random.Next(10,
100));
Draw();
}
private void ButtonCreateTrain_Click(object sender, EventArgs e)
{
Random random = new();
Color color = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
Color dopColor = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog2 = new();
if (dialog2.ShowDialog() == DialogResult.OK)
{
color = dialog2.Color;
}
_drawningRoadTrain = new DrawningTrain(random.Next(100, 300),
random.Next(1000, 3000), color,
dopColor, Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)),
pictureBoxRoadTrain.Width, pictureBoxRoadTrain.Height);
_drawningRoadTrain.SetPosition(random.Next(10, 100), random.Next(10,
100));
Draw();
}
private void ButtonSelectTrain_Click(object sender, EventArgs e)
{
SelectedTrain = _drawningRoadTrain;
DialogResult = DialogResult.OK;
}
} }
} }

133
RoadTrain/FormTrainCollection.Designer.cs generated Normal file
View File

@ -0,0 +1,133 @@
namespace RoadTrain
{
partial class FormTrainCollection
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
panel1 = new Panel();
InputTextBox = new TextBox();
ButtonRefreshCollection = new Button();
ButtonRemoveTrain = new Button();
ButtonAddTrain = new Button();
label1 = new Label();
pictureBoxCollection = new PictureBox();
panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
SuspendLayout();
//
// panel1
//
panel1.Controls.Add(InputTextBox);
panel1.Controls.Add(ButtonRefreshCollection);
panel1.Controls.Add(ButtonRemoveTrain);
panel1.Controls.Add(ButtonAddTrain);
panel1.Controls.Add(label1);
panel1.Location = new Point(597, 12);
panel1.Name = "panel1";
panel1.Size = new Size(200, 426);
panel1.TabIndex = 0;
//
// InputTextBox
//
InputTextBox.Location = new Point(49, 118);
InputTextBox.Name = "InputTextBox";
InputTextBox.Size = new Size(100, 23);
InputTextBox.TabIndex = 4;
//
// ButtonRefreshCollection
//
ButtonRefreshCollection.Location = new Point(39, 233);
ButtonRefreshCollection.Name = "ButtonRefreshCollection";
ButtonRefreshCollection.Size = new Size(126, 44);
ButtonRefreshCollection.TabIndex = 3;
ButtonRefreshCollection.Text = "Обновить коллекцию";
ButtonRefreshCollection.UseVisualStyleBackColor = true;
ButtonRefreshCollection.Click += ButtonRefreshCollection_Click;
//
// ButtonRemoveTrain
//
ButtonRemoveTrain.Location = new Point(39, 160);
ButtonRemoveTrain.Name = "ButtonRemoveTrain";
ButtonRemoveTrain.Size = new Size(126, 30);
ButtonRemoveTrain.TabIndex = 2;
ButtonRemoveTrain.Text = "Удалить поезд";
ButtonRemoveTrain.UseVisualStyleBackColor = true;
ButtonRemoveTrain.Click += ButtonRemoveTrain_Click;
//
// ButtonAddTrain
//
ButtonAddTrain.Location = new Point(39, 45);
ButtonAddTrain.Name = "ButtonAddTrain";
ButtonAddTrain.Size = new Size(126, 33);
ButtonAddTrain.TabIndex = 1;
ButtonAddTrain.Text = "Добавить поезд";
ButtonAddTrain.UseVisualStyleBackColor = true;
ButtonAddTrain.Click += ButtonAddTrain_Click;
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(66, 14);
label1.Name = "label1";
label1.Size = new Size(83, 15);
label1.TabIndex = 0;
label1.Text = "Инструменты";
//
// pictureBoxCollection
//
pictureBoxCollection.Location = new Point(0, 1);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(591, 446);
pictureBoxCollection.TabIndex = 1;
pictureBoxCollection.TabStop = false;
//
// FormTrainCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(pictureBoxCollection);
Controls.Add(panel1);
Name = "FormTrainCollection";
Text = "FormTrainCollection";
panel1.ResumeLayout(false);
panel1.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
ResumeLayout(false);
}
#endregion
private Panel panel1;
private Button ButtonAddTrain;
private Label label1;
private TextBox InputTextBox;
private Button ButtonRefreshCollection;
private Button ButtonRemoveTrain;
private PictureBox pictureBoxCollection;
}
}

View File

@ -0,0 +1,70 @@
using RoadTrain.DrawningObjects;
using RoadTrain.Generics;
using RoadTrain.MovementStrategy;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace RoadTrain
{
public partial class FormTrainCollection : Form
{
private readonly RoadTrainGenericCollection<DrawningRoadTrain,
DrawningObjectTrain> _trains;
public FormTrainCollection()
{
InitializeComponent();
_trains = new RoadTrainGenericCollection<DrawningRoadTrain,
DrawningObjectTrain>(pictureBoxCollection.Width, pictureBoxCollection.Height);
}
private void ButtonAddTrain_Click(object sender, EventArgs e)
{
FormRoadTrain form = new();
if (form.ShowDialog() == DialogResult.OK)
{
if (_trains + form.SelectedTrain != -1)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = _trains.ShowTrains();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
}
private void ButtonRemoveTrain_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(InputTextBox.Text);
if (_trains - pos != null)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = _trains.ShowTrains();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
{
pictureBoxCollection.Image = _trains.ShowTrains();
}
}
}

View File

@ -0,0 +1,120 @@
<?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:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -11,7 +11,7 @@ namespace RoadTrain
// To customize application configuration such as set high DPI settings or default font, // To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new FormRoadTrain()); Application.Run(new FormTrainCollection());
} }
} }
} }

88
RoadTrain/SetGeneric.cs Normal file
View File

@ -0,0 +1,88 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RoadTrain.Generics
{
internal class SetGeneric<T>
where T : class
{
/// <summary>
/// Массив объектов, которые храним
/// </summary>
private readonly T?[] _places;
/// <summary>
/// Количество объектов в массиве
/// </summary>
public int Count => _places.Length;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetGeneric(int count)
{
_places = new T?[count];
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="car">Добавляемый автомобиль</param>
/// <returns></returns>
public int Insert(T train)
{
for (int i = Count - 1; i >= 1; i--)
{
if (_places[i - 1] == null)
continue;
_places[i] = _places[i - 1];
}
_places[0] = train;
return 0;
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="car">Добавляемый автомобиль</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public int Insert(T train, int position)
{
if ((position < 0) && (position > Count)) return -1;
if (_places[position] != null)
{
for (int i = Count - 1; i >= position; i--)
{
if (_places[i - 1] != null)
_places[i] = _places[i - 1];
}
}
_places[position] = train;
return position;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public bool Remove(int position)
{
if ((position < 0) || (position > Count)) return false;
_places[position] = null;
return true;
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T? Get(int position)
{
if ((position < 0) || (position > Count)) return null;
return _places[position];
}
}
}

View File

@ -0,0 +1,141 @@
using RoadTrain.Generics;
using RoadTrain.MovementStrategy;
using System;
using RoadTrain.DrawningObjects;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RoadTrain.Generics
{
internal class RoadTrainGenericCollection<T, U>
where T : DrawningRoadTrain
where U : IMoveableObject
{
/// <summary>
/// Ширина окна прорисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна прорисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Размер занимаемого объектом места (ширина)
/// </summary>
private readonly int _placeSizeWidth = 110;
/// <summary>
/// Размер занимаемого объектом места (высота)
/// </summary>
private readonly int _placeSizeHeight = 50;
/// <summary>
/// Набор объектов
/// </summary>
private readonly SetGeneric<T> _collection;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
public RoadTrainGenericCollection(int picWidth, int picHeight)
{
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = new SetGeneric<T>(width * height);
}
/// <summary>
/// Перегрузка оператора сложения
/// </summary>
/// <param name="collect"></param>
/// <param name="obj"></param>
/// <returns></returns>
public static int operator +(RoadTrainGenericCollection<T, U> collect, T?
obj)
{
if (obj == null)
{
return -1;
}
return collect._collection.Insert(obj);
}
/// <summary>
/// Перегрузка оператора вычитания
/// </summary>
/// <param name="collect"></param>
/// <param name="pos"></param>
/// <returns></returns>
public static T? operator -(RoadTrainGenericCollection<T, U> collect, int
pos)
{
T? obj = collect._collection.Get(pos);
if (obj != null)
{
collect._collection.Remove(pos);
}
return obj;
}
/// <summary>
/// Получение объекта IMoveableObject
/// </summary>
/// <param name="pos"></param>
/// <returns></returns>
public U? GetU(int pos)
{
return (U?)_collection.Get(pos)?.GetMoveableObject;
}
/// <summary>
/// Вывод всего набора объектов
/// </summary>
/// <returns></returns>
public Bitmap ShowTrains()
{
Bitmap bmp = new(_pictureWidth, _pictureHeight);
Graphics gr = Graphics.FromImage(bmp);
DrawBackground(gr);
DrawObjects(gr);
return bmp;
}
/// <summary>
/// Метод отрисовки фона
/// </summary>
/// <param name="g"></param>
private void DrawBackground(Graphics g)
{
Pen pen = new(Color.Black, 3);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight +
1; ++j)
{//линия рамзетки места
g.DrawLine(pen, i * _placeSizeWidth, j *
_placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth / 2, j *
_placeSizeHeight);
}
g.DrawLine(pen, i * _placeSizeWidth, 0, i *
_placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight);
}
}
/// <summary>
/// Метод прорисовки объектов
/// </summary>
/// <param name="g"></param>
private void DrawObjects(Graphics g)
{
{
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
for (int i = 0; i < _collection.Count; i++)
{
DrawningRoadTrain? tank = _collection.Get(i);
if (tank == null)
continue;
tank.SetPosition(i % width * _placeSizeWidth, i / width * _placeSizeHeight);
tank.DrawTransport(g);
}
}
}
}
}