завершенная laba3

This commit is contained in:
Extrimal 2023-10-31 20:14:22 +03:00
parent ea56167cc9
commit ce4eb04c93
9 changed files with 542 additions and 12 deletions

View File

@ -0,0 +1,103 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AircraftCarrier.DrawningObjects;
using AircraftCarrier.MovementStrategy;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace AircraftCarrier.Generics
{
internal class AircraftsGenericCollection<T, U>
where T : DrawningAircraft
where U : IMoveableObject
{
/// Ширина окна прорисовки
private readonly int _pictureWidth;
/// Высота окна прорисовки
private readonly int _pictureHeight;
/// Размер занимаемого объектом места (ширина)
private readonly int _placeSizeWidth = 210;
/// Размер занимаемого объектом места (высота)
private readonly int _placeSizeHeight = 90;
/// Набор объектов
private readonly SetGeneric<T> _collection;
/// Конструктор
public AircraftsGenericCollection(int picWidth, int picHeight)
{
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = new SetGeneric<T>(width * height);
}
/// Перегрузка оператора сложения
public static int operator + (AircraftsGenericCollection<T, U> collect, T?
obj)
{
if (obj == null)
{
return -1;
}
return collect._collection.Insert(obj);
}
/// Перегрузка оператора вычитания
public static bool operator - (AircraftsGenericCollection<T, U> collect, int pos)
{
T? obj = collect._collection.Get(pos);
if (obj != null)
{
return collect._collection.Remove(pos);
}
return false;
}
/// Получение объекта IMoveableObject
public U? GetU(int pos)
{
return (U?)_collection.Get(pos)?.GetMoveableObject;
}
/// Вывод всего набора объектов
public Bitmap ShowAircraft()
{
Bitmap bmp = new(_pictureWidth, _pictureHeight);
Graphics gr = Graphics.FromImage(bmp);
DrawBackground(gr);
DrawObjects(gr);
return bmp;
}
/// Метод отрисовки фона
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);
}
}
/// Метод прорисовки объектов
private void DrawObjects(Graphics g)
{
int inRow = _pictureWidth / _placeSizeWidth;
for (int i = 0; i < _collection.Count; i++)
{
DrawningAircraft aircraft = _collection.Get(i);
if (aircraft != null)
{
aircraft.SetPosition(i % inRow * _placeSizeWidth+3, (_collection.Count / inRow - 1 - i / inRow) * _placeSizeHeight+20);
aircraft.DrawTransport(g);
}
}
}
}
}

View File

@ -4,6 +4,8 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AircraftCarrier.Entities;
using AircraftCarrier.MovementStrategy;
namespace AircraftCarrier.DrawningObjects
{
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
@ -30,6 +32,8 @@ namespace AircraftCarrier.DrawningObjects
/// Проверка, что объект может переместится по указанному направлению
/// <param name="direction">Направление</param>
/// <returns>true - можно переместится по указанному направлению</returns>
public IMoveableObject GetMoveableObject => new DrawningObjectAircraft(this);
public bool CanMove(Direction direction)
{
if (EntityAircraft == null)

View File

@ -37,6 +37,7 @@
ButtonCreateAircraft = new Button();
comboBoxStrategy = new ComboBox();
buttonStep = new Button();
buttonSelectAircraft = new Button();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
SuspendLayout();
//
@ -143,11 +144,22 @@
buttonStep.UseVisualStyleBackColor = true;
buttonStep.Click += buttonStep_Click;
//
// buttonSelectAircraft
//
buttonSelectAircraft.Location = new Point(457, 393);
buttonSelectAircraft.Name = "buttonSelectAircraft";
buttonSelectAircraft.Size = new Size(204, 39);
buttonSelectAircraft.TabIndex = 10;
buttonSelectAircraft.Text = "Выбрать объект";
buttonSelectAircraft.UseVisualStyleBackColor = true;
buttonSelectAircraft.Click += buttonSelectAircraft_Click;
//
// FormAircraftCarrier
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(882, 453);
Controls.Add(buttonSelectAircraft);
Controls.Add(buttonStep);
Controls.Add(comboBoxStrategy);
Controls.Add(ButtonCreateAircraft);
@ -176,5 +188,6 @@
private Button ButtonCreateAircraftCarrier;
private ComboBox comboBoxStrategy;
private Button buttonStep;
private Button buttonSelectAircraft;
}
}

View File

@ -9,9 +9,12 @@ namespace AircraftCarrier
private DrawningAircraft? _drawingAircraft;
private AbstractStrategy? _abstractStrategy;
public DrawningAircraft? SelectedAircraft { get; private set; }
public FormAircraftCarrier()
{
InitializeComponent();
_abstractStrategy = null;
SelectedAircraft = null;
}
private void Draw()
{
@ -52,11 +55,15 @@ namespace AircraftCarrier
private void ButtonCreateAircraft_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;
}
_drawingAircraft = new DrawningAircraft(random.Next(100, 300),
random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256),
random.Next(0, 256)),
pictureBox.Width, pictureBox.Height);
random.Next(1000, 3000), color, pictureBox.Width, pictureBox.Height);
_drawingAircraft.SetPosition(random.Next(10, 100), random.Next(10,
100));
Draw();
@ -65,10 +72,21 @@ namespace AircraftCarrier
private void ButtonCreateAircraftCarrier_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 colorDialog = new ColorDialog();
if (colorDialog.ShowDialog() == DialogResult.OK)
{
color = colorDialog.Color;
}
Color dopColor = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
if (colorDialog.ShowDialog() == DialogResult.OK)
{
dopColor = colorDialog.Color;
}
_drawingAircraft = new DrawningAircraftCarrier(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)),
color, dopColor, Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)), pictureBox.Width, pictureBox.Height);
_drawingAircraft.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
@ -93,15 +111,14 @@ namespace AircraftCarrier
{
return;
}
_abstractStrategy.SetData(new
DrawningObjectAircraft(_drawingAircraft), pictureBox.Width,
pictureBox.Height);
comboBoxStrategy.Enabled = false;
_abstractStrategy.SetData(_drawingAircraft.GetMoveableObject,
pictureBox.Width, pictureBox.Height);
}
if (_abstractStrategy == null)
{
return;
}
comboBoxStrategy.Enabled = false;
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
@ -111,5 +128,10 @@ namespace AircraftCarrier
}
}
private void buttonSelectAircraft_Click(object sender, EventArgs e)
{
SelectedAircraft = _drawingAircraft;
DialogResult = DialogResult.OK;
}
}
}

View File

@ -0,0 +1,136 @@
namespace AircraftCarrier
{
partial class FormAircraftCollection
{
/// <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()
{
PictureBoxCollection = new PictureBox();
PanelTools = new Panel();
ButtonRefreshCollection = new Button();
ButtonRemoveAircraft = new Button();
MaskedTextBoxNumber = new MaskedTextBox();
ButtonAddAircraft = new Button();
LabelTools = new Label();
((System.ComponentModel.ISupportInitialize)PictureBoxCollection).BeginInit();
PanelTools.SuspendLayout();
SuspendLayout();
//
// PictureBoxCollection
//
PictureBoxCollection.Location = new Point(0, 0);
PictureBoxCollection.Name = "PictureBoxCollection";
PictureBoxCollection.Size = new Size(599, 450);
PictureBoxCollection.TabIndex = 0;
PictureBoxCollection.TabStop = false;
//
// PanelTools
//
PanelTools.BorderStyle = BorderStyle.FixedSingle;
PanelTools.Controls.Add(ButtonRefreshCollection);
PanelTools.Controls.Add(ButtonRemoveAircraft);
PanelTools.Controls.Add(MaskedTextBoxNumber);
PanelTools.Controls.Add(ButtonAddAircraft);
PanelTools.Location = new Point(599, 12);
PanelTools.Name = "PanelTools";
PanelTools.Size = new Size(202, 438);
PanelTools.TabIndex = 1;
//
// ButtonRefreshCollection
//
ButtonRefreshCollection.Location = new Point(15, 206);
ButtonRefreshCollection.Name = "ButtonRefreshCollection";
ButtonRefreshCollection.Size = new Size(168, 41);
ButtonRefreshCollection.TabIndex = 3;
ButtonRefreshCollection.Text = "Обновить коллекцию";
ButtonRefreshCollection.UseVisualStyleBackColor = true;
ButtonRefreshCollection.Click += ButtonRefreshCollection_Click;
//
// ButtonRemoveAircraft
//
ButtonRemoveAircraft.Location = new Point(15, 137);
ButtonRemoveAircraft.Name = "ButtonRemoveAircraft";
ButtonRemoveAircraft.Size = new Size(168, 41);
ButtonRemoveAircraft.TabIndex = 2;
ButtonRemoveAircraft.Text = "Удалить судно";
ButtonRemoveAircraft.UseVisualStyleBackColor = true;
ButtonRemoveAircraft.Click += ButtonRemoveAircraft_Click;
//
// MaskedTextBoxNumber
//
MaskedTextBoxNumber.Location = new Point(36, 95);
MaskedTextBoxNumber.Name = "MaskedTextBoxNumber";
MaskedTextBoxNumber.Size = new Size(125, 27);
MaskedTextBoxNumber.TabIndex = 1;
MaskedTextBoxNumber.Text = "_";
//
// ButtonAddAircraft
//
ButtonAddAircraft.Location = new Point(15, 19);
ButtonAddAircraft.Name = "ButtonAddAircraft";
ButtonAddAircraft.Size = new Size(168, 41);
ButtonAddAircraft.TabIndex = 0;
ButtonAddAircraft.Text = "Добавить судно";
ButtonAddAircraft.UseVisualStyleBackColor = true;
ButtonAddAircraft.Click += ButtonAddAircraft_Click;
//
// LabelTools
//
LabelTools.AutoSize = true;
LabelTools.Location = new Point(615, 0);
LabelTools.Name = "LabelTools";
LabelTools.Size = new Size(103, 20);
LabelTools.TabIndex = 0;
LabelTools.Text = "Инструменты";
//
// FormAircraftCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(LabelTools);
Controls.Add(PanelTools);
Controls.Add(PictureBoxCollection);
Name = "FormAircraftCollection";
Text = "FormAircraftCollection";
((System.ComponentModel.ISupportInitialize)PictureBoxCollection).EndInit();
PanelTools.ResumeLayout(false);
PanelTools.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
private PictureBox PictureBoxCollection;
private Panel PanelTools;
private MaskedTextBox MaskedTextBoxNumber;
private Button ButtonAddAircraft;
private Label LabelTools;
private Button ButtonRefreshCollection;
private Button ButtonRemoveAircraft;
}
}

View File

@ -0,0 +1,65 @@
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;
using AircraftCarrier.DrawningObjects;
using AircraftCarrier.Generics;
using AircraftCarrier.MovementStrategy;
namespace AircraftCarrier
{
public partial class FormAircraftCollection : Form
{
private readonly AircraftsGenericCollection<DrawningAircraft, DrawningObjectAircraft> _Aircrafts;
public FormAircraftCollection()
{
InitializeComponent();
_Aircrafts = new AircraftsGenericCollection<DrawningAircraft, DrawningObjectAircraft>(PictureBoxCollection.Width, PictureBoxCollection.Height);
}
private void ButtonAddAircraft_Click(object sender, EventArgs e)
{
FormAircraftCarrier form = new();
if (form.ShowDialog() == DialogResult.OK)
{
if (_Aircrafts + form.SelectedAircraft != -1)
{
MessageBox.Show("Объект добавлен");
PictureBoxCollection.Image = _Aircrafts.ShowAircraft();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
}
private void ButtonRemoveAircraft_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(MaskedTextBoxNumber.Text);
if (_Aircrafts - pos != null)
{
MessageBox.Show("Объект удален");
PictureBoxCollection.Image = _Aircrafts.ShowAircraft();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
{
PictureBoxCollection.Image = _Aircrafts.ShowAircraft();
}
}
}

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

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

View File

@ -0,0 +1,67 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AircraftCarrier.Generics
{
internal class SetGeneric<T>
where T : class
{
/// Массив объектов, которые храним
private readonly T?[] _places;
/// Количество объектов в массиве
public int Count => _places.Length;
/// Конструктор
public SetGeneric(int count)
{
_places = new T?[count];
}
/// Добавление объекта в набор
public int Insert(T Aircraft)
{
return Insert(Aircraft, 0);
}
/// Добавление объекта в набор на конкретную позицию
public int Insert(T Aircraft, int position)
{
int nullIndex = -1, i;
if (position < 0 || position >= Count)
return -1;
for (i = position; i < Count; i++)
{
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] = Aircraft;
return position;
}
/// Удаление объекта из набора с конкретной позиции
public bool Remove(int position)
{
if (position < 0 || position >= Count) return false;
_places[position] = null;
return true;
}
/// Получение объекта из набора по позиции
public T? Get(int position)
{
if (position < 0 || position >= Count)
return null;
return _places[position];
}
}
}