Compare commits

..

2 Commits

Author SHA1 Message Date
Efi
0f508fa568 Лабораторная работа 3 2023-03-31 23:16:35 +04:00
Efi
1883c5f919 до логики формы 2023-03-31 21:55:40 +04:00
15 changed files with 817 additions and 35 deletions

View File

@ -0,0 +1,51 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Monorail
{
internal class BushesMap : AbstractMap
{
private readonly Pen barrierColor = new Pen(Color.DarkGreen, 3);
private readonly Brush roadColor = new SolidBrush(Color.Brown);
protected override void DrawBarrierPart(Graphics g, int i, int j)
{
g.DrawLine(barrierColor, new Point(Convert.ToInt32(i * (_size_x - 1)), Convert.ToInt32(j * (_size_y - 1))), new Point(Convert.ToInt32(i * (_size_x - 1) + 7), Convert.ToInt32(j * (_size_y - 1)) + 7));
g.DrawLine(barrierColor, new Point(Convert.ToInt32(i * (_size_x - 1) + 7), Convert.ToInt32(j * (_size_y - 1))), new Point(Convert.ToInt32(i * (_size_x - 1) + 7), Convert.ToInt32(j * (_size_y - 1)) + 7));
g.DrawLine(barrierColor, new Point(Convert.ToInt32(i * (_size_x - 1) + 7), Convert.ToInt32(j * (_size_y - 1)) + 7), new Point(Convert.ToInt32(i * (_size_x - 1) + 14), Convert.ToInt32(j * (_size_y - 1))));
}
protected override void DrawRoadPart(Graphics g, int i, int j)
{
g.FillRectangle(roadColor, i * _size_x, j * _size_y, i * (_size_x + 1), j * (_size_y + 1));
}
protected override void GenerateMap()
{
_map = new int[100, 100];
_size_x = (float)_width / _map.GetLength(0);
_size_y = (float)_height / _map.GetLength(1);
int counter = 0;
for (int i = 0; i < _map.GetLength(0); ++i)
{
for (int j = 0; j < _map.GetLength(1); ++j)
{
_map[i, j] = _freeRoad;
}
}
while (counter < 20)
{
int x = _random.Next(0, 100);
int y = _random.Next(0, 100);
if (_map[x, y] == _freeRoad)
{
_map[x, y] = _barrier;
counter++;
}
}
}
}
}

View File

@ -6,7 +6,7 @@ using System.Threading.Tasks;
namespace Monorail namespace Monorail
{ {
internal enum Direction public enum Direction
{ {
None = 0, None = 0,
Up = 1, Up = 1,

View File

@ -6,7 +6,7 @@ using System.Threading.Tasks;
namespace Monorail namespace Monorail
{ {
internal class DrawingLocomotive public class DrawingLocomotive
{ {
public EntityLocomotive Locomotive { get; protected set; } public EntityLocomotive Locomotive { get; protected set; }
protected float _startPosX; protected float _startPosX;
@ -98,7 +98,7 @@ namespace Monorail
Locomotive = new EntityLocomotive(speed, weight, bodyColor); Locomotive = new EntityLocomotive(speed, weight, bodyColor);
} }
protected DrawingLocomotive(int speed, float weight, Color bodyColor, int locomotiveWidth, int locomotiveHeight) : public DrawingLocomotive(int speed, float weight, Color bodyColor, int locomotiveWidth, int locomotiveHeight) :
this(speed, weight, bodyColor) this(speed, weight, bodyColor)
{ {
_locomotiveWidth = locomotiveWidth; _locomotiveWidth = locomotiveWidth;

View File

@ -6,7 +6,7 @@ using System.Threading.Tasks;
namespace Monorail namespace Monorail
{ {
internal class EntityLocomotive public class EntityLocomotive
{ {
public int Speed { get; private set; } public int Speed { get; private set; }
public float Weight { get; private set; } public float Weight { get; private set; }

View File

@ -0,0 +1,47 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Monorail
{
internal class FieldMap : AbstractMap
{
private readonly Brush barrierColor = new SolidBrush(Color.Brown);
private readonly Brush roadColor = new SolidBrush(Color.Green);
protected override void DrawBarrierPart(Graphics g, int i, int j)
{
g.FillEllipse(barrierColor, i * (_size_x - 1), j * (_size_y - 1), 30, 15);
}
protected override void DrawRoadPart(Graphics g, int i, int j)
{
g.FillRectangle(roadColor, i * _size_x, j * _size_y, i * (_size_x), j * (_size_y));
}
protected override void GenerateMap()
{
_map = new int[100, 100];
_size_x = (float)_width / _map.GetLength(0);
_size_y = (float)_height / _map.GetLength(1);
int counter = 0;
for (int i = 0; i < _map.GetLength(0); ++i)
{
for (int j = 0; j < _map.GetLength(1); ++j)
{
_map[i, j] = _freeRoad;
}
}
while (counter < 20)
{
int x = _random.Next(0, 100);
int y = _random.Next(0, 100);
if (_map[x, y] == _freeRoad)
{
_map[x, y] = _barrier;
counter++;
}
}
}
}
}

View File

@ -39,6 +39,8 @@
buttonLeft = new Button(); buttonLeft = new Button();
buttonRight = new Button(); buttonRight = new Button();
buttonDown = new Button(); buttonDown = new Button();
buttonCreateModify = new Button();
ButtonSelectLocomotive = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxLocomotive).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxLocomotive).BeginInit();
statusStrip.SuspendLayout(); statusStrip.SuspendLayout();
SuspendLayout(); SuspendLayout();
@ -139,11 +141,33 @@
buttonDown.UseVisualStyleBackColor = true; buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += ButtonMove_Click; buttonDown.Click += ButtonMove_Click;
// //
// buttonCreateModify
//
buttonCreateModify.Location = new Point(93, 390);
buttonCreateModify.Name = "buttonCreateModify";
buttonCreateModify.Size = new Size(152, 23);
buttonCreateModify.TabIndex = 7;
buttonCreateModify.Text = "Модифицировать";
buttonCreateModify.UseVisualStyleBackColor = true;
buttonCreateModify.Click += ButtonCreateModify_Click;
//
// ButtonSelectLocomotive
//
ButtonSelectLocomotive.Location = new Point(635, 12);
ButtonSelectLocomotive.Name = "ButtonSelectLocomotive";
ButtonSelectLocomotive.Size = new Size(153, 33);
ButtonSelectLocomotive.TabIndex = 8;
ButtonSelectLocomotive.Text = "Выбрать";
ButtonSelectLocomotive.UseVisualStyleBackColor = true;
ButtonSelectLocomotive.Click += ButtonSelectLocomotive_Click;
//
// FormLocomotive // FormLocomotive
// //
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(ButtonSelectLocomotive);
Controls.Add(buttonCreateModify);
Controls.Add(buttonDown); Controls.Add(buttonDown);
Controls.Add(buttonRight); Controls.Add(buttonRight);
Controls.Add(buttonLeft); Controls.Add(buttonLeft);
@ -172,5 +196,7 @@
private Button buttonLeft; private Button buttonLeft;
private Button buttonRight; private Button buttonRight;
private Button buttonDown; private Button buttonDown;
private Button buttonCreateModify;
private Button ButtonSelectLocomotive;
} }
} }

View File

@ -13,19 +13,11 @@ namespace Monorail
public partial class FormLocomotive : Form public partial class FormLocomotive : Form
{ {
private DrawingLocomotive _locomotive; private DrawingLocomotive _locomotive;
public DrawingLocomotive SelectedLocomotive { get; private set; }
public FormLocomotive() public FormLocomotive()
{ {
InitializeComponent(); InitializeComponent();
} }
private void ButtonCreate_Click(object sender, EventArgs e)
{
Random rnd = new();
_locomotive = new DrawingLocomotive(rnd.Next(100, 300), rnd.Next(1000, 2000), Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256)));
SetData();
Draw();
}
private void Draw() private void Draw()
{ {
Bitmap bmp = new(pictureBoxLocomotive.Width, pictureBoxLocomotive.Height); Bitmap bmp = new(pictureBoxLocomotive.Width, pictureBoxLocomotive.Height);
@ -33,16 +25,31 @@ namespace Monorail
_locomotive?.DrawTransport(gr); _locomotive?.DrawTransport(gr);
pictureBoxLocomotive.Image = bmp; pictureBoxLocomotive.Image = bmp;
} }
/// <summary> private void SetData()
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü" {
/// </summary> Random rnd = new();
/// <param name="sender"></param> _locomotive.SetPosition(rnd.Next(10, 100), rnd.Next(10, 100),
/// <param name="e"></param> pictureBoxLocomotive.Width, pictureBoxLocomotive.Height);
/// <summary> toolStripStatusLabelSpeed.Text = $"Ńęîđîńňü: {_locomotive.Locomotive.Speed}";
/// Èçìåíåíèå ðàçìåðîâ ôîðìû toolStripStatusLabelWeight.Text = $"Âĺń: {_locomotive.Locomotive.Weight}";
/// </summary> toolStripStatusLabelBodyColor.Text = $"Öâĺň: {_locomotive.Locomotive.BodyColor.Name} ";
/// <param name="sender"></param> }
/// <param name="e"></param> private void ButtonCreate_Click(object sender, EventArgs e)
{
Random rnd = new();
Color color = Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256),
rnd.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
_locomotive = new DrawingLocomotive(rnd.Next(100, 300), rnd.Next(1000, 2000),
color);
SetData();
Draw();
}
private void ButtonMove_Click(object sender, EventArgs e) private void ButtonMove_Click(object sender, EventArgs e)
{ {
//ïîëó÷àåì èìÿ êíîïêè //ïîëó÷àåì èìÿ êíîïêè
@ -64,25 +71,40 @@ namespace Monorail
} }
Draw(); Draw();
} }
/// <summary>
/// Èçìåíåíèå ðàçìåðîâ ôîðìû
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PictureBoxLocomotive_Resize(object sender, EventArgs e) private void PictureBoxLocomotive_Resize(object sender, EventArgs e)
{ {
_locomotive?.ChangeBorders(pictureBoxLocomotive.Width, pictureBoxLocomotive.Height); _locomotive?.ChangeBorders(pictureBoxLocomotive.Width, pictureBoxLocomotive.Height);
Draw(); Draw();
} }
private void SetData() private void ButtonCreateModify_Click(object sender, EventArgs e)
{ {
Random rnd = new(); Random rnd = new();
_locomotive.SetPosition(rnd.Next(10, 100), rnd.Next(10, 100), pictureBoxLocomotive.Width, pictureBoxLocomotive.Height); Color color = Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256),
toolStripStatusLabelSpeed.Text = $"Ñêîðîñòü: {_locomotive.Locomotive.Speed}"; rnd.Next(0, 256));
toolStripStatusLabelWeight.Text = $"Âåñ: {_locomotive.Locomotive.Weight}"; ColorDialog dialog = new();
toolStripStatusLabelBodyColor.Text = $"Öâåò: {_locomotive.Locomotive.BodyColor.Name}"; if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
Color dopColor = Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256),
rnd.Next(0, 256));
ColorDialog dialogDop = new();
if (dialogDop.ShowDialog() == DialogResult.OK)
{
dopColor = dialogDop.Color;
}
_locomotive = new DrawingMonorailLocomotive(rnd.Next(100, 300), rnd.Next(1000, 2000),
color, dopColor, Convert.ToBoolean(rnd.Next(0, 2)), Convert.ToBoolean(rnd.Next(0, 2)));
SetData();
Draw();
} }
private void ButtonSelectLocomotive_Click(object sender, EventArgs e)
{
SelectedLocomotive = _locomotive;
DialogResult = DialogResult.OK;
}
} }
} }

View File

@ -154,7 +154,7 @@
// //
comboBoxSelectorMap.DropDownStyle = ComboBoxStyle.DropDownList; comboBoxSelectorMap.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorMap.FormattingEnabled = true; comboBoxSelectorMap.FormattingEnabled = true;
comboBoxSelectorMap.Items.AddRange(new object[] { "SimpleMap" }); comboBoxSelectorMap.Items.AddRange(new object[] { "Простая карта", "Поле с грязью", "Кусты на карте" });
comboBoxSelectorMap.Location = new Point(12, 12); comboBoxSelectorMap.Location = new Point(12, 12);
comboBoxSelectorMap.Name = "comboBoxSelectorMap"; comboBoxSelectorMap.Name = "comboBoxSelectorMap";
comboBoxSelectorMap.Size = new Size(121, 23); comboBoxSelectorMap.Size = new Size(121, 23);

View File

@ -91,6 +91,12 @@ namespace Monorail
case "Простая карта": case "Простая карта":
_abstractMap = new SimpleMap(); _abstractMap = new SimpleMap();
break; break;
case "Поле с грязью":
_abstractMap = new FieldMap();
break;
case "Кусты на карте":
_abstractMap = new BushesMap();
break;
} }
} }

View File

@ -0,0 +1,208 @@
namespace Monorail
{
partial class FormMapWithSetLocomotive
{
/// <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()
{
pictureBoxLocomotive = new PictureBox();
comboBoxSelectorMap = new ComboBox();
buttonAddCar = new Button();
buttonRemoveCar = new Button();
buttonShowStorage = new Button();
buttonShowOnMap = new Button();
maskedTextBoxPosition = new MaskedTextBox();
buttonUp = new Button();
buttonLeft = new Button();
buttonDown = new Button();
buttonRight = new Button();
groupBoxTools = new GroupBox();
((System.ComponentModel.ISupportInitialize)pictureBoxLocomotive).BeginInit();
groupBoxTools.SuspendLayout();
SuspendLayout();
//
// pictureBoxLocomotive
//
pictureBoxLocomotive.Dock = DockStyle.Left;
pictureBoxLocomotive.Location = new Point(0, 0);
pictureBoxLocomotive.Name = "pictureBoxLocomotive";
pictureBoxLocomotive.Size = new Size(579, 450);
pictureBoxLocomotive.TabIndex = 0;
pictureBoxLocomotive.TabStop = false;
//
// comboBoxSelectorMap
//
comboBoxSelectorMap.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorMap.FormattingEnabled = true;
comboBoxSelectorMap.Items.AddRange(new object[] { "Простая карта", "Карта с грязью", "Карта с кустами" });
comboBoxSelectorMap.Location = new Point(26, 22);
comboBoxSelectorMap.Name = "comboBoxSelectorMap";
comboBoxSelectorMap.Size = new Size(168, 23);
comboBoxSelectorMap.TabIndex = 2;
comboBoxSelectorMap.SelectedIndexChanged += ComboBoxSelectorMap_SelectedIndexChanged;
//
// buttonAddCar
//
buttonAddCar.Location = new Point(26, 70);
buttonAddCar.Name = "buttonAddCar";
buttonAddCar.Size = new Size(168, 28);
buttonAddCar.TabIndex = 3;
buttonAddCar.Text = "Добавить локомотив";
buttonAddCar.UseVisualStyleBackColor = true;
buttonAddCar.Click += ButtonAddLocomotive_Click;
//
// buttonRemoveCar
//
buttonRemoveCar.Location = new Point(26, 151);
buttonRemoveCar.Name = "buttonRemoveCar";
buttonRemoveCar.Size = new Size(169, 30);
buttonRemoveCar.TabIndex = 4;
buttonRemoveCar.Text = "Удалить локомотив";
buttonRemoveCar.UseVisualStyleBackColor = true;
buttonRemoveCar.Click += ButtonRemoveLocomotive_Click;
//
// buttonShowStorage
//
buttonShowStorage.Location = new Point(26, 222);
buttonShowStorage.Name = "buttonShowStorage";
buttonShowStorage.Size = new Size(168, 39);
buttonShowStorage.TabIndex = 5;
buttonShowStorage.Text = "Посмотреть хранилище";
buttonShowStorage.UseVisualStyleBackColor = true;
buttonShowStorage.Click += ButtonShowStorage_Click;
//
// buttonShowOnMap
//
buttonShowOnMap.Location = new Point(26, 307);
buttonShowOnMap.Name = "buttonShowOnMap";
buttonShowOnMap.Size = new Size(169, 34);
buttonShowOnMap.TabIndex = 6;
buttonShowOnMap.Text = "Посмотреть карту";
buttonShowOnMap.UseVisualStyleBackColor = true;
buttonShowOnMap.Click += ButtonShowOnMap_Click;
//
// maskedTextBoxPosition
//
maskedTextBoxPosition.Location = new Point(26, 193);
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(168, 23);
maskedTextBoxPosition.TabIndex = 7;
//
// buttonUp
//
buttonUp.BackgroundImage = Properties.Resources.arrowUp;
buttonUp.BackgroundImageLayout = ImageLayout.Zoom;
buttonUp.Location = new Point(98, 366);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(30, 30);
buttonUp.TabIndex = 8;
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += ButtonMove_Click;
//
// buttonLeft
//
buttonLeft.BackgroundImage = Properties.Resources.arrowLeft;
buttonLeft.BackgroundImageLayout = ImageLayout.Zoom;
buttonLeft.Location = new Point(62, 402);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(30, 30);
buttonLeft.TabIndex = 9;
buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.Click += ButtonMove_Click;
//
// buttonDown
//
buttonDown.BackgroundImage = Properties.Resources.arrowDown;
buttonDown.BackgroundImageLayout = ImageLayout.Zoom;
buttonDown.Location = new Point(98, 402);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(30, 30);
buttonDown.TabIndex = 10;
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += ButtonMove_Click;
//
// buttonRight
//
buttonRight.BackgroundImage = Properties.Resources.arrowRight;
buttonRight.BackgroundImageLayout = ImageLayout.Zoom;
buttonRight.Location = new Point(134, 402);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(30, 30);
buttonRight.TabIndex = 11;
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click;
//
// groupBoxTools
//
groupBoxTools.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
groupBoxTools.Controls.Add(buttonRight);
groupBoxTools.Controls.Add(buttonDown);
groupBoxTools.Controls.Add(buttonLeft);
groupBoxTools.Controls.Add(buttonUp);
groupBoxTools.Controls.Add(maskedTextBoxPosition);
groupBoxTools.Controls.Add(buttonShowOnMap);
groupBoxTools.Controls.Add(buttonShowStorage);
groupBoxTools.Controls.Add(buttonRemoveCar);
groupBoxTools.Controls.Add(buttonAddCar);
groupBoxTools.Controls.Add(comboBoxSelectorMap);
groupBoxTools.Location = new Point(585, -2);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(212, 451);
groupBoxTools.TabIndex = 12;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// FormMapWithSetLocomotive
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(groupBoxTools);
Controls.Add(pictureBoxLocomotive);
Name = "FormMapWithSetLocomotive";
Text = "Карта с набором объектов";
((System.ComponentModel.ISupportInitialize)pictureBoxLocomotive).EndInit();
groupBoxTools.ResumeLayout(false);
groupBoxTools.PerformLayout();
ResumeLayout(false);
}
#endregion
private PictureBox pictureBoxLocomotive;
private ComboBox comboBoxSelectorMap;
private Button buttonAddCar;
private Button buttonRemoveCar;
private Button buttonShowStorage;
private Button buttonShowOnMap;
private MaskedTextBox maskedTextBoxPosition;
private Button buttonUp;
private Button buttonLeft;
private Button buttonDown;
private Button buttonRight;
private GroupBox groupBoxTools;
}
}

View File

@ -0,0 +1,131 @@
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 Monorail
{
public partial class FormMapWithSetLocomotive : Form
{
private MapWithSetLocomotiveGeneric <DrawingObjectLocomotive, AbstractMap> _mapLocomotivesCollectionGeneric;
public FormMapWithSetLocomotive()
{
InitializeComponent();
}
private void ComboBoxSelectorMap_SelectedIndexChanged(object sender,
EventArgs e)
{
AbstractMap map = null;
switch (comboBoxSelectorMap.Text)
{
case "Простая карта":
map = new SimpleMap();
break;
case "Карта с грязью":
map = new FieldMap();
break;
case "Карта с кустами":
map = new BushesMap();
break;
}
if (map != null)
{
_mapLocomotivesCollectionGeneric = new MapWithSetLocomotiveGeneric<DrawingObjectLocomotive, AbstractMap>(pictureBoxLocomotive.Width, pictureBoxLocomotive.Height, map);
}
else
{
_mapLocomotivesCollectionGeneric = null;
}
}
private void ButtonAddLocomotive_Click(object sender, EventArgs e)
{
if (_mapLocomotivesCollectionGeneric == null)
{
return;
}
FormLocomotive form = new();
if (form.ShowDialog() == DialogResult.OK)
{
DrawingObjectLocomotive Locomotive = new(form.SelectedLocomotive);
if (_mapLocomotivesCollectionGeneric + Locomotive != -1)
{
MessageBox.Show("Объект добавлен");
pictureBoxLocomotive.Image = _mapLocomotivesCollectionGeneric.ShowSet();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
}
private void ButtonRemoveLocomotive_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text))
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_mapLocomotivesCollectionGeneric - pos != null)
{
MessageBox.Show("Объект удален");
pictureBoxLocomotive.Image = _mapLocomotivesCollectionGeneric.ShowSet();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
private void ButtonShowStorage_Click(object sender, EventArgs e)
{
if (_mapLocomotivesCollectionGeneric == null)
{
return;
}
pictureBoxLocomotive.Image = _mapLocomotivesCollectionGeneric.ShowSet();
}
private void ButtonShowOnMap_Click(object sender, EventArgs e)
{
if (_mapLocomotivesCollectionGeneric == null)
{
return;
}
pictureBoxLocomotive.Image = _mapLocomotivesCollectionGeneric.ShowOnMap();
}
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_mapLocomotivesCollectionGeneric == null)
{
return;
}
//получаем имя кнопки
string name = ((Button)sender)?.Name ?? string.Empty;
Direction dir = Direction.None;
switch (name)
{
case "buttonUp":
dir = Direction.Up;
break;
case "buttonDown":
dir = Direction.Down;
break;
case "buttonLeft":
dir = Direction.Left;
break;
case "buttonRight":
dir = Direction.Right;
break;
}
pictureBoxLocomotive.Image = _mapLocomotivesCollectionGeneric.MoveObject(dir);
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<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

@ -0,0 +1,151 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Monorail
{
internal class MapWithSetLocomotiveGeneric<T, U>
where T : class, IDrawingObject
where U : AbstractMap
{
// Ширина окна отрисовки
private readonly int _pictureWidth;
// Высота окна отрисовки
private readonly int _pictureHeight;
// Размер занимаемого объектом места (ширина)
private readonly int _placeSizeWidth = 180;
// Размер занимаемого объектом места (высота)
private readonly int _placeSizeHeight = 150;
// Набор объектов
private readonly SetLocomotivGeneric<T> _setLocomotive;
// Карта
private readonly U _map;
private readonly T[] _places;
// Конструктор
public MapWithSetLocomotiveGeneric(int picWidth, int picHeight, U map)
{
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_setLocomotive = new SetLocomotivGeneric<T>(width * height);
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_map = map;
}
// Перегрузка оператора сложения
public static int operator +(MapWithSetLocomotiveGeneric<T, U> map, T Locomotive)
{
return map._setLocomotive.Insert(Locomotive);
}
// Перегрузка оператора вычитания
public static T operator -(MapWithSetLocomotiveGeneric<T, U> map, int position)
{
return map._setLocomotive.Remove(position);
}
// Вывод всего набора объектов
public Bitmap ShowSet()
{
Bitmap bmp = new(_pictureWidth, _pictureHeight);
Graphics gr = Graphics.FromImage(bmp);
DrawBackground(gr);
DrawLocomotive(gr);
return bmp;
}
// Просмотр объекта на карте
public Bitmap ShowOnMap()
{
Shaking();
for (int i = 0; i < _setLocomotive.Count; i++)
{
var Locomotive = _setLocomotive.Get(i);
if (Locomotive != null)
{
return _map.CreateMap(_pictureWidth, _pictureHeight, Locomotive);
}
}
return new(_pictureWidth, _pictureHeight);
}
// Перемещение объекта по карте
public Bitmap MoveObject(Direction direction)
{
if (_map != null)
{
return _map.MoveObject(direction);
}
return new(_pictureWidth, _pictureHeight);
}
// "Взбалтываем" набор, чтобы все элементы оказались в начале
private void Shaking()
{
int j = _setLocomotive.Count - 1;
for (int i = 0; i < _setLocomotive.Count; i++)
{
if (_setLocomotive.Get(i) == null)
{
for (; j > i; j--)
{
var Locomotive = _setLocomotive.Get(j);
if (Locomotive != null)
{
_setLocomotive.Insert(Locomotive, i);
_setLocomotive.Remove(j);
break;
}
}
if (j <= i)
{
return;
}
}
}
}
// Метод отрисовки фона
private void DrawBackground(Graphics g)
{
Pen pen = new(Color.Sienna, 3);
Brush brush = new SolidBrush(Color.DodgerBlue);
g.FillRectangle(brush, 0, 0, _pictureWidth, _pictureHeight);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j)
{
g.DrawLine(pen, i * _placeSizeWidth, j * _placeSizeHeight + 2, i * _placeSizeWidth + _placeSizeWidth / 2 + 40, j * _placeSizeHeight + 2);
}
g.DrawLine(pen, i * _placeSizeWidth + 7, 2, i * _placeSizeWidth + 7, (_pictureHeight / _placeSizeHeight) * _placeSizeHeight);
g.DrawLine(pen, i * _placeSizeWidth + 3, 2, i * _placeSizeWidth + 3, (_pictureHeight / _placeSizeHeight) * _placeSizeHeight);
}
}
// Метод прорисовки объектов
private void DrawLocomotive(Graphics g)
{
int widthEl = _pictureWidth / _placeSizeWidth;
int heightEl = _pictureHeight / _placeSizeHeight;
int curWidth = 0;
int curHeight = 0;
for (int i = _setLocomotive.Count; i >= 0; i--)
{
_setLocomotive.Get(i)?.SetObject(_pictureWidth - _placeSizeWidth * curWidth - 85,
curHeight * _placeSizeHeight + 10, _pictureWidth, _pictureHeight);
_setLocomotive.Get(i)?.DrawingObject(g);
if (curWidth < widthEl)
curWidth++;
else
{
curWidth = 1;
curHeight++;
}
if (curHeight > heightEl)
{
return;
}
}
}
}
}

View File

@ -11,7 +11,7 @@ namespace Monorail
// 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 FormMap()); Application.Run(new FormMapWithSetLocomotive());
} }
} }
} }

View File

@ -0,0 +1,80 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Monorail
{
internal class SetLocomotivGeneric<T>
where T : class
{
// Массив объектов, которые храним
private readonly T[] _places;
// Количество объектов в массиве
public int Count => _places.Length;
// Конструктор
public SetLocomotivGeneric(int count)
{
_places = new T[count];
}
// Добавление объекта в набор
public int Insert(T Locomotive)
{
// вставка в начало набора
return Insert(Locomotive, 0);
}
// Добавление объекта в набор на конкретную позицию
public int Insert(T Locomotive, int position)
{
// проверка позиции
if (position >= _places.Length || position < 0)
return -1;
//проверка, что элемент массива по этой позиции пустой, если нет, то
if (_places[position] == null)
{
_places[position] = Locomotive;
return position;
}
//проверка, что после вставляемого элемента в массиве есть пустой элемент
int findEmptyPos = -1;
for (int i = position + 1; i < Count; i++)
{
if (_places[i] == null)
{
findEmptyPos = i;
break;
}
}
if (findEmptyPos < 0) return -1;
//сдвиг всех объектов, находящихся справа от позиции до первого пустого элемента
for (int i = findEmptyPos; i > position; i--)
{
_places[i] = _places[i - 1];
}
// вставка по позиции
_places[position] = Locomotive;
return position;
}
// Удаление объекта из набора с конкретной позиции
public T Remove(int position)
{
// проверка позиции
if (position >= _places.Length || position < 0) return null;
// удаление объекта из массива, присовив элементу массива значение null
T temp = _places[position];
_places[position] = null;
return temp;
}
// Получение объекта из набора по позиции
public T Get(int position)
{
// проверка позиции
if (position >= _places.Length || position < 0)
return null;
return _places[position];
}
}
}