Compare commits

..

No commits in common. "lab4" and "main" have entirely different histories.
lab4 ... main

33 changed files with 81 additions and 2275 deletions

View File

@ -8,19 +8,4 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
</Project>

View File

@ -3,7 +3,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.7.34024.191
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Cruiser", "Cruiser.csproj", "{4B55C43E-7DDF-4DA6-A186-7244085169A8}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Cruiser", "Cruiser.csproj", "{756E194C-4DC4-4A91-A93C-3E903FABED76}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -11,15 +11,15 @@ Global
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4B55C43E-7DDF-4DA6-A186-7244085169A8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4B55C43E-7DDF-4DA6-A186-7244085169A8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4B55C43E-7DDF-4DA6-A186-7244085169A8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4B55C43E-7DDF-4DA6-A186-7244085169A8}.Release|Any CPU.Build.0 = Release|Any CPU
{756E194C-4DC4-4A91-A93C-3E903FABED76}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{756E194C-4DC4-4A91-A93C-3E903FABED76}.Debug|Any CPU.Build.0 = Debug|Any CPU
{756E194C-4DC4-4A91-A93C-3E903FABED76}.Release|Any CPU.ActiveCfg = Release|Any CPU
{756E194C-4DC4-4A91-A93C-3E903FABED76}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {45C16C6A-A71C-4A65-8704-F821496C7C82}
SolutionGuid = {034E99D7-3DC1-49BB-86DA-3314CC18DE34}
EndGlobalSection
EndGlobal

View File

@ -1,28 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cruiser
{
public enum Direction
{
/// <summary>
/// Вверх
/// </summary>
Up = 1,
/// <summary>
/// Вниз
/// </summary>
Down = 2,
/// <summary>
/// Влево
/// </summary>
Left = 3,
/// <summary>
/// Вправо
/// </summary>
Right = 4
}
}

View File

@ -1,218 +0,0 @@
using Cruiser.Entities;
using Cruiser.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cruiser.Drawing
{
public class DrawingCruiser
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityCruiser? EntityCruiser { get; set; }
/// <summary>
/// Ширина окна
/// </summary>
private int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int _pictureHeight;
/// <summary>
/// Левая координата прорисовки Крейсера
/// </summary>
protected static int _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки Крейсера
/// </summary>
protected static int _startPosY;
/// <summary>
/// Ширина прорисовки Крейсера
/// </summary>
private readonly int _cruiserWidth = 150;
/// <summary>
/// Высота прорисовки Крейсера
/// </summary>
private readonly int _cruiserHeight = 60;
/// <summary>
/// Координата X объекта
/// </summary>
public int GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _cruiserWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _cruiserHeight;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="secColor">Элементов цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public DrawingCruiser(int speed, double weight, Color bodyColor, Color secColor, int width, int height)
{
if (width < _cruiserWidth || height < _cruiserHeight)
{
_pictureHeight = _cruiserHeight + 100;
_pictureWidth = _cruiserWidth + 100;
}
_pictureWidth = width;
_pictureHeight = height;
EntityCruiser = new EntityCruiser(speed, weight, bodyColor, secColor);
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="secColor">Элементов цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <param name="cruiserWidth">Ширина прорисовки крейсера</param>
/// <param name="cruiserHeight">Высота прорисовки крейсера</param>
public DrawingCruiser(int speed, double weight, Color bodyColor, Color secColor, int width, int height, int cruiserWidth, int cruiserHeight)
{
_pictureWidth = width;
_pictureHeight = height;
_cruiserHeight = cruiserHeight;
_cruiserWidth = cruiserWidth;
EntityCruiser = new EntityCruiser(speed, weight, bodyColor, secColor);
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
/// <summary>
/// Получение объекта IMoveableObject из объекта DrawningCar
/// </summary>
public IMoveableObject GetMoveableObject => new
DrawningObjectCar(this);
public void SetPosition(int x, int y)
{
if (x < 0 || y < 0)
{
return;
}
if (x > _pictureWidth || y > _pictureHeight)
{
return;
}
_startPosX = x;
_startPosY = y;
}
/// <summary>
/// Проверка, что объект может переместится по указанному направлению
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - можно переместится по указанному направлению</returns>
public bool CanMove(Direction direction)
{
if (EntityCruiser == null)
{
return false;
}
return direction switch
{
//влево
Direction.Left => _startPosX - EntityCruiser.Step > 0,
//вверх
Direction.Up => _startPosY - EntityCruiser.Step > 0,
// вправо
Direction.Right => _startPosX + EntityCruiser.Step + _cruiserWidth < _pictureWidth,
//вниз
Direction.Down => _startPosY + EntityCruiser.Step + _cruiserHeight < _pictureHeight,
};
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
public void MoveTransport(Direction direction)
{
if (!CanMove(direction) || EntityCruiser == null)
{
return;
}
switch (direction)
{
//влево
case Direction.Left:
_startPosX -= (int)EntityCruiser.Step;
break;
//вверх
case Direction.Up:
_startPosY -= (int)EntityCruiser.Step;
break;
// вправо
case Direction.Right:
_startPosX += (int)EntityCruiser.Step;
break;
//вниз
case Direction.Down:
_startPosY += (int)EntityCruiser.Step;
break;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public virtual void DrawTransport(Graphics g)
{
if (EntityCruiser == null)
{
return;
}
// палуба
Point[] Paluba = new Point[5]
{
new Point(_startPosX + 10,_startPosY),
new Point(_startPosX + 110,_startPosY),
new Point(_startPosX + 160,_startPosY + 30),
new Point(_startPosX + 110,_startPosY + 60),
new Point(_startPosX + 10,_startPosY + 60)
};
Brush brush = new SolidBrush(EntityCruiser.BodyColor);
g.FillPolygon(brush, Paluba);
// элементы
Point[] Elements = new Point[8]
{
new Point(_startPosX + 50,_startPosY + 20),
new Point(_startPosX + 70,_startPosY + 20),
new Point(_startPosX + 70,_startPosY + 10),
new Point(_startPosX + 90,_startPosY + 10),
new Point(_startPosX + 90,_startPosY + 50),
new Point(_startPosX + 70,_startPosY + 50),
new Point(_startPosX + 70,_startPosY + 40),
new Point(_startPosX + 50,_startPosY + 40),
};
Brush brushElem = new SolidBrush(EntityCruiser.SecondColor);
g.FillPolygon(brushElem, Elements);
g.FillEllipse(brushElem, _startPosX + 100, _startPosY + 20, 20, 20);
// турбины
Brush Turbins = new SolidBrush(Color.Black);
g.FillRectangle(Turbins, _startPosX, _startPosY + 10, 10, 20);
g.FillRectangle(Turbins, _startPosX, _startPosY + 35, 10, 20);
}
}
}

View File

@ -1,41 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cruiser.Entities;
namespace Cruiser.Drawing
{
public class DrawingProCruiser : DrawingCruiser
{
public DrawingProCruiser(int speed, double weight, Color bodyColor, Color secColor, Color elemColor, bool rocketMines, bool helipad, int width, int height) :
base (speed, weight, bodyColor, secColor, width, height, 150, 60)
{
if (EntityCruiser != null)
{
EntityCruiser = new EntityProCruiser(speed, weight, bodyColor, secColor, elemColor, rocketMines, helipad);
}
}
public override void DrawTransport(Graphics g)
{
if (EntityCruiser is not EntityProCruiser cruiser)
{
return;
}
base.DrawTransport(g);
Brush DopBrush = new SolidBrush(cruiser.ElementsColor);
// шахты
if (cruiser.RocketMines)
{
g.FillRectangle(DopBrush, _startPosX + 15, _startPosY + 10, 10, 15);
g.FillRectangle(DopBrush, _startPosX + 30, _startPosY + 10, 10, 15);
}
// верт площадка
if (cruiser.Helipad)
{
g.FillEllipse(DopBrush, _startPosX + 15, _startPosY + 25, 25, 25);
}
}
}
}

View File

@ -1,46 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cruiser.Entities
{
/// <summary>
/// Класс-сущность "Крейсер"
/// </summary>
public class EntityCruiser
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; }
/// <summary>
/// Второстепенный цвет
/// </summary>
public Color SecondColor { get; private set; }
/// <summary>
/// Шаг перемещения Крейсера
/// </summary>
public double Step => (double)Speed * 100 / Weight;
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес Крейсера</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="secColor">Второстепенный цвет</param>
public EntityCruiser(int speed, double weight, Color bodyColor, Color secColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
SecondColor = secColor;
}
}
}

View File

@ -1,41 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cruiser.Entities
{
public class EntityProCruiser : EntityCruiser
{
/// <summary>
/// Элементов цвет
/// </summary>
public Color ElementsColor { get; private set; }
/// <summary>
/// Признак (опция) наличия ракетных шахт
/// </summary>
public bool RocketMines { get; private set; }
/// <summary>
/// Признак (опция) наличия вертолётной площадки
/// </summary>
public bool Helipad { get; private set; }
/// <summary>
/// Инициализация полей объекта-класса спортивного крейсера
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес Крейсера</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="secColor">Второстепенный цвет</param>
/// <param name="elemColor">Элементов цвет</param>
/// <param name="rocketMines">Признак наличия ракетных шахт</param>
/// <param name="helipad">Признак наличия вертолётной площадки</param>
public EntityProCruiser(int speed, double weight, Color bodyColor, Color secColor, Color elemColor, bool rocketMines, bool helipad) :
base(speed, weight, bodyColor, secColor)
{
RocketMines = rocketMines;
Helipad = helipad;
ElementsColor = elemColor;
}
}
}

39
Cruiser/Form1.Designer.cs generated Normal file
View File

@ -0,0 +1,39 @@
namespace Cruiser
{
partial class Form1
{
/// <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()
{
this.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Text = "Form1";
}
#endregion
}
}

10
Cruiser/Form1.cs Normal file
View File

@ -0,0 +1,10 @@
namespace Cruiser
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}

View File

@ -1,182 +0,0 @@
namespace Cruiser
{
partial class FormCruiser
{
/// <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()
{
pictureBoxCruiser = new PictureBox();
buttonCreateLiner = new Button();
buttonRight = new Button();
buttonDown = new Button();
buttonLeft = new Button();
buttonUp = new Button();
buttonCreateProLiner = new Button();
comboBoxStrategy = new ComboBox();
ButtonStep = new Button();
buttonSelectCruiser = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxCruiser).BeginInit();
SuspendLayout();
//
// pictureBoxCruiser
//
pictureBoxCruiser.Dock = DockStyle.Fill;
pictureBoxCruiser.Location = new Point(0, 0);
pictureBoxCruiser.Name = "pictureBoxCruiser";
pictureBoxCruiser.Size = new Size(800, 450);
pictureBoxCruiser.TabIndex = 0;
pictureBoxCruiser.TabStop = false;
//
// buttonCreateLiner
//
buttonCreateLiner.Location = new Point(12, 396);
buttonCreateLiner.Name = "buttonCreateLiner";
buttonCreateLiner.Size = new Size(125, 48);
buttonCreateLiner.TabIndex = 1;
buttonCreateLiner.Text = "Создать Лайнер";
buttonCreateLiner.UseVisualStyleBackColor = true;
buttonCreateLiner.Click += buttonCreateLiner_Click;
//
// buttonRight
//
buttonRight.BackgroundImage = Properties.Resources.Right;
buttonRight.BackgroundImageLayout = ImageLayout.Zoom;
buttonRight.Location = new Point(758, 408);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(30, 30);
buttonRight.TabIndex = 2;
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += ButtonMove_Click;
//
// buttonDown
//
buttonDown.BackgroundImage = Properties.Resources.Down;
buttonDown.BackgroundImageLayout = ImageLayout.Zoom;
buttonDown.Location = new Point(722, 408);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(30, 30);
buttonDown.TabIndex = 3;
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += ButtonMove_Click;
//
// buttonLeft
//
buttonLeft.BackgroundImage = Properties.Resources.Left;
buttonLeft.BackgroundImageLayout = ImageLayout.Zoom;
buttonLeft.Location = new Point(686, 408);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(30, 30);
buttonLeft.TabIndex = 4;
buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.Click += ButtonMove_Click;
//
// buttonUp
//
buttonUp.BackgroundImage = Properties.Resources.Up;
buttonUp.BackgroundImageLayout = ImageLayout.Zoom;
buttonUp.Location = new Point(722, 372);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(30, 30);
buttonUp.TabIndex = 5;
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += ButtonMove_Click;
//
// buttonCreateProLiner
//
buttonCreateProLiner.Location = new Point(143, 396);
buttonCreateProLiner.Name = "buttonCreateProLiner";
buttonCreateProLiner.Size = new Size(125, 48);
buttonCreateProLiner.TabIndex = 6;
buttonCreateProLiner.Text = "Создать Лютый Лайнер";
buttonCreateProLiner.UseVisualStyleBackColor = true;
buttonCreateProLiner.Click += buttonCreateProLiner_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "MoveToCenter", "MoveToBorder" });
comboBoxStrategy.Location = new Point(667, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(121, 23);
comboBoxStrategy.TabIndex = 7;
//
// ButtonStep
//
ButtonStep.Location = new Point(713, 41);
ButtonStep.Name = "ButtonStep";
ButtonStep.Size = new Size(75, 23);
ButtonStep.TabIndex = 8;
ButtonStep.Text = "Шаг";
ButtonStep.UseVisualStyleBackColor = true;
ButtonStep.Click += ButtonStep_Click;
//
// buttonSelectCruiser
//
buttonSelectCruiser.Location = new Point(274, 396);
buttonSelectCruiser.Name = "buttonSelectCruiser";
buttonSelectCruiser.Size = new Size(127, 48);
buttonSelectCruiser.TabIndex = 9;
buttonSelectCruiser.Text = "Выбрать этот лайнер";
buttonSelectCruiser.UseVisualStyleBackColor = true;
buttonSelectCruiser.Click += ButtonSelectCruiser_Click;
//
// FormCruiser
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(buttonSelectCruiser);
Controls.Add(ButtonStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateProLiner);
Controls.Add(buttonUp);
Controls.Add(buttonLeft);
Controls.Add(buttonDown);
Controls.Add(buttonRight);
Controls.Add(buttonCreateLiner);
Controls.Add(pictureBoxCruiser);
Name = "FormCruiser";
Text = "Cruiser";
Load += FormCruiser_Load;
((System.ComponentModel.ISupportInitialize)pictureBoxCruiser).EndInit();
ResumeLayout(false);
}
#endregion
private PictureBox pictureBoxCruiser;
private Button buttonCreateLiner;
private Button buttonRight;
private Button buttonDown;
private Button buttonLeft;
private Button buttonUp;
private Button buttonCreateProLiner;
private ComboBox comboBoxStrategy;
private Button ButtonStep;
private Button buttonSelectCruiser;
}
}

View File

@ -1,185 +0,0 @@
using System;
using Cruiser.Drawing;
using Cruiser.Entities;
using Cruiser.MovementStrategy;
namespace Cruiser
{
public partial class FormCruiser : Form
{
Bitmap bmp;
/// <summary>
/// Ïîëå-îáúåêò äëÿ ïðîðèñîâêè îáúåêòà
/// </summary>
private DrawingCruiser? _drawningCruiser;
/// <summary>
/// Ñòðàòåãèÿ ïåðåìåùåíèÿ
/// </summary>
private AbstractStrategy? _abstractStrategy;
/// <summary>
/// Âûáðàííûé ëàéíåð
/// </summary>
public DrawingCruiser? SelectedCruiser { get; private set; }
/// <summary>
/// Èíèöèàëèçàöèÿ ôîðìû
/// </summary>
public FormCruiser()
{
InitializeComponent();
bmp = new(pictureBoxCruiser.Width, pictureBoxCruiser.Width);
_abstractStrategy = null;
SelectedCruiser = null;
}
/// <summary>
/// Ìåòîä ïðîðèñîâêè êðåéñåðà
/// </summary>
private void Draw()
{
if (_drawningCruiser == null)
{
return;
}
Graphics gr = Graphics.FromImage(bmp);
gr.Clear(Color.White);
_drawningCruiser.DrawTransport(gr);
pictureBoxCruiser.Image = bmp;
}
/// <summary>
/// Èçìåíåíèå ïîëîæåíèÿ àâòîìîáèëÿ
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawningCruiser == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
switch (name)
{
case "buttonUp":
_drawningCruiser.MoveTransport(Direction.Up);
break;
case "buttonDown":
_drawningCruiser.MoveTransport(Direction.Down);
break;
case "buttonLeft":
_drawningCruiser.MoveTransport(Direction.Left);
break;
case "buttonRight":
_drawningCruiser.MoveTransport(Direction.Right);
break;
}
Draw();
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Øàã"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonStep_Click(object sender, EventArgs e)
{
if (_drawningCruiser == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_abstractStrategy = comboBoxStrategy.SelectedIndex
switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(new
DrawningObjectCar(_drawningCruiser), pictureBoxCruiser.Width,
pictureBoxCruiser.Height);
comboBoxStrategy.Enabled = false;
}
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_abstractStrategy = null;
}
}
private void buttonCreateLiner_Click(object sender, EventArgs e)
{
Random random = new();
Color colorFirst = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
colorFirst = dialog.Color;
}
_drawningCruiser = new DrawingCruiser(random.Next(100, 300),
random.Next(1000, 3000),
colorFirst,
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
pictureBoxCruiser.Width,
pictureBoxCruiser.Height);
_drawningCruiser.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
private void buttonCreateProLiner_Click(object sender, EventArgs e)
{
Random random = new();
Color colorFirst = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
colorFirst = dialog.Color;
}
Color colorSecond = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
if (dialog.ShowDialog() == DialogResult.OK)
{
colorSecond = dialog.Color;
}
_drawningCruiser = new DrawingProCruiser(random.Next(100, 300),
random.Next(1000, 3000),
colorFirst,
colorSecond,
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
Convert.ToBoolean(random.Next(1, 2)),
Convert.ToBoolean(random.Next(1, 2)),
pictureBoxCruiser.Width,
pictureBoxCruiser.Height);
_drawningCruiser.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
/// <summary>
/// Âûáîð ëàéíåð
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSelectCruiser_Click(object sender, EventArgs e)
{
SelectedCruiser = _drawningCruiser;
DialogResult = DialogResult.OK;
}
private void FormCruiser_Load(object sender, EventArgs e)
{
}
}
}

View File

@ -1,120 +0,0 @@
<?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

@ -1,188 +0,0 @@
namespace Cruiser
{
partial class FormCruiserCollection
{
/// <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()
{
groupBoxTools = new GroupBox();
buttonDeleteCruiser = new Button();
textBoxNumber = new TextBox();
buttonAddCruiser = new Button();
buttonRefreshCollection = new Button();
pictureBoxCollection = new PictureBox();
groupBoxStorage = new GroupBox();
listBoxStorages = new ListBox();
buttonDelObject = new Button();
textBoxStorageName = new TextBox();
buttonAddObject = new Button();
groupBoxTools.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
groupBoxStorage.SuspendLayout();
SuspendLayout();
//
// groupBoxTools
//
groupBoxTools.Controls.Add(buttonDeleteCruiser);
groupBoxTools.Controls.Add(textBoxNumber);
groupBoxTools.Controls.Add(buttonAddCruiser);
groupBoxTools.Location = new Point(653, 1);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(148, 140);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// buttonDeleteCruiser
//
buttonDeleteCruiser.Location = new Point(15, 95);
buttonDeleteCruiser.Name = "buttonDeleteCruiser";
buttonDeleteCruiser.Size = new Size(122, 37);
buttonDeleteCruiser.TabIndex = 2;
buttonDeleteCruiser.Text = "Удалить лайнер";
buttonDeleteCruiser.UseVisualStyleBackColor = true;
buttonDeleteCruiser.Click += ButtonRemoveCar_Click;
//
// textBoxNumber
//
textBoxNumber.Location = new Point(15, 66);
textBoxNumber.Name = "textBoxNumber";
textBoxNumber.Size = new Size(122, 23);
textBoxNumber.TabIndex = 1;
//
// buttonAddCruiser
//
buttonAddCruiser.Location = new Point(15, 22);
buttonAddCruiser.Name = "buttonAddCruiser";
buttonAddCruiser.Size = new Size(122, 38);
buttonAddCruiser.TabIndex = 0;
buttonAddCruiser.Text = "Добавить лайнер";
buttonAddCruiser.UseVisualStyleBackColor = true;
buttonAddCruiser.Click += buttonAddCruiser_Click;
//
// buttonRefreshCollection
//
buttonRefreshCollection.Location = new Point(662, 397);
buttonRefreshCollection.Name = "buttonRefreshCollection";
buttonRefreshCollection.Size = new Size(131, 41);
buttonRefreshCollection.TabIndex = 3;
buttonRefreshCollection.Text = "Обновить коллекцию";
buttonRefreshCollection.UseVisualStyleBackColor = true;
buttonRefreshCollection.Click += ButtonRefreshCollection_Click;
//
// pictureBoxCollection
//
pictureBoxCollection.Location = new Point(14, 1);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(642, 448);
pictureBoxCollection.TabIndex = 1;
pictureBoxCollection.TabStop = false;
//
// groupBoxStorage
//
groupBoxStorage.Controls.Add(listBoxStorages);
groupBoxStorage.Controls.Add(buttonDelObject);
groupBoxStorage.Controls.Add(textBoxStorageName);
groupBoxStorage.Controls.Add(buttonAddObject);
groupBoxStorage.Location = new Point(662, 139);
groupBoxStorage.Name = "groupBoxStorage";
groupBoxStorage.Size = new Size(136, 252);
groupBoxStorage.TabIndex = 2;
groupBoxStorage.TabStop = false;
groupBoxStorage.Text = "Наборы";
//
// listBoxStorages
//
listBoxStorages.FormattingEnabled = true;
listBoxStorages.ItemHeight = 15;
listBoxStorages.Location = new Point(10, 117);
listBoxStorages.Name = "listBoxStorages";
listBoxStorages.Size = new Size(120, 124);
listBoxStorages.TabIndex = 7;
listBoxStorages.SelectedIndexChanged += ListBoxObjects_SelectedIndexChanged;
//
// buttonDelObject
//
buttonDelObject.Location = new Point(8, 86);
buttonDelObject.Name = "buttonDelObject";
buttonDelObject.Size = new Size(122, 25);
buttonDelObject.TabIndex = 2;
buttonDelObject.Text = "Удалить набор";
buttonDelObject.UseVisualStyleBackColor = true;
buttonDelObject.Click += ButtonDelObject_Click;
//
// textBoxStorageName
//
textBoxStorageName.Location = new Point(8, 22);
textBoxStorageName.Name = "textBoxStorageName";
textBoxStorageName.Size = new Size(122, 23);
textBoxStorageName.TabIndex = 1;
//
// buttonAddObject
//
buttonAddObject.Location = new Point(8, 52);
buttonAddObject.Name = "buttonAddObject";
buttonAddObject.Size = new Size(122, 28);
buttonAddObject.TabIndex = 0;
buttonAddObject.Text = "Добавить набор";
buttonAddObject.UseVisualStyleBackColor = true;
buttonAddObject.Click += ButtonAddObject_Click;
//
// FormCruiserCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(buttonRefreshCollection);
Controls.Add(groupBoxStorage);
Controls.Add(pictureBoxCollection);
Controls.Add(groupBoxTools);
Name = "FormCruiserCollection";
Text = "Набор Крейсеров";
Load += FormCruiserCollection_Load;
groupBoxTools.ResumeLayout(false);
groupBoxTools.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
groupBoxStorage.ResumeLayout(false);
groupBoxStorage.PerformLayout();
ResumeLayout(false);
}
#endregion
private GroupBox groupBoxTools;
private TextBox textBoxNumber;
private Button buttonAddCruiser;
private Button buttonRefreshCollection;
private Button buttonDeleteCruiser;
private PictureBox pictureBoxCollection;
private GroupBox groupBoxStorage;
private Button buttonDelObject;
private TextBox textBoxStorageName;
private Button buttonAddObject;
private ListBox listBoxStorages;
}
}

View File

@ -1,188 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Cruiser.Drawing;
using Cruiser.Generics;
using Cruiser.MovementStrategy;
namespace Cruiser
{
/// <summary>
/// Форма для работы с набором объектов класса DrawingCruiser
/// </summary>
public partial class FormCruiserCollection : Form
{
/// <summary>
/// Набор объектов
/// </summary>
private readonly CruisersGenericStorage _storage;
/// <summary>
/// Конструктор
/// </summary>
public FormCruiserCollection()
{
InitializeComponent();
_storage = new CruisersGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
}
/// <summary>
/// Заполнение listBoxObjects
/// </summary>
private void ReloadObjects()
{
int index = listBoxStorages.SelectedIndex;
listBoxStorages.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++)
{
listBoxStorages.Items.Add(_storage.Keys[i]);
}
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 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>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ListBoxObjects_SelectedIndexChanged(object sender,
EventArgs e)
{
pictureBoxCollection.Image = _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowCruiser();
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAddCruiser_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
FormCruiser form = new();
if (form.ShowDialog() == DialogResult.OK)
{
if (obj + form.SelectedCruiser)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowCruiser();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
}
/// <summary>
/// Удаление объекта из набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveCar_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(textBoxNumber.Text);
if (obj - pos != null)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowCruiser();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
/// <summary>
/// Обновление рисунка по набору
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
pictureBoxCollection.Image = obj.ShowCruiser();
}
private void FormCruiserCollection_Load(object sender, EventArgs e)
{
}
}
}

View File

@ -1,143 +0,0 @@
using Cruiser.MovementStrategy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cruiser.Drawing;
namespace Cruiser.Generics
{
/// <summary>
/// Параметризованный класс для набора объектов DrawingCruiser
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
internal class CarsGenericCollection<T, U>
where T : DrawingCruiser
where U : IMoveableObject
{
/// <summary>
/// Ширина окна прорисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна прорисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Размер занимаемого объектом места (ширина)
/// </summary>
private readonly int _placeSizeWidth = 160;
/// <summary>
/// Размер занимаемого объектом места (высота)
/// </summary>
private readonly int _placeSizeHeight = 60;
/// <summary>
/// Набор объектов
/// </summary>
private readonly SetGeneric<T> _collection;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
public CarsGenericCollection(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 bool operator +(CarsGenericCollection<T, U> collect, T? obj)
{
if (obj == null)
{
return false;
}
return collect._collection.Insert(obj);
}
/// <summary>
/// Перегрузка оператора вычитания
/// </summary>
/// <param name="collect"></param>
/// <param name="pos"></param>
/// <returns></returns>
public static T? operator -(CarsGenericCollection<T, U> collect, int pos)
{
T? obj = collect._collection[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[pos]?.GetMoveableObject;
}
/// <summary>
/// Вывод всего набора объектов
/// </summary>
/// <returns></returns>
public Bitmap ShowCruiser()
{
Bitmap bmp = new(_pictureWidth, _pictureHeight);
Graphics gr = Graphics.FromImage(bmp);
DrawObjects(gr);
DrawBackground(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; j++)
{
g.DrawRectangle(pen, i * _placeSizeWidth, j * _placeSizeHeight, _placeSizeWidth, _placeSizeHeight);
}
}
}
/// <summary>
/// /// Метод прорисовки объектов
/// </summary>
/// <param name="g"></param>
private void DrawObjects(Graphics g)
{
int Ix = 0;
int Iy = 0;
int i = 0;
foreach (var cruiser in _collection.GetCruisers())
{
_collection[i]?.SetPosition(Ix, Iy);
_collection[i]?.DrawTransport(g);
Ix += _placeSizeWidth;
if (Ix + _placeSizeHeight > _pictureWidth)
{
Ix = 0;
Iy = _placeSizeHeight;
}
i++;
}
}
}
}

View File

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

View File

@ -1,108 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.Eventing.Reader;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cruiser.Generics
{
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T"></typeparam>
internal class SetGeneric<T>
where T : class
{
/// <summary>
/// Список объектов, которые храним
/// </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)
{
_maxCount = count;
_places = new List<T?>(count);
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="cruiser">Добавляемый лайнер</param>
/// <returns></returns>
public bool Insert(T cruiser)
{
if (_places.Count + 1 <= _maxCount)
{
_places.Insert(0, cruiser);
}
return true;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public bool Remove(int position)
{
if (position < 0 || position > _places.Count)
{
return false;
}
_places[position] = null;
return true;
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="cruiser">Добавляемый автомобиль</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public bool Insert(T cruiser, int position)
{
if (_places.Count + 1 <= _maxCount && _places.Count >= position)
{
_places.Insert(position, cruiser);
return true;
}
return false;
}
public T? this[int position]
{
get
{
if (position < 0 || position > _maxCount)
{ return null; }
return _places[position];
}
set
{
if (position < 0 || position > _maxCount)
return;
_places[position] = value;
}
}
public IEnumerable<T?> GetCruisers(int? maxCruisers = null)
{
for (int i = 0; i < _places.Count; ++i)
{
yield return _places[i];
if (maxCruisers.HasValue && i == maxCruisers.Value)
{
yield break;
}
}
}
}
}

View File

@ -1,138 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cruiser.Drawing;
namespace Cruiser.MovementStrategy
{
/// <summary>
/// Класс-стратегия перемещения объекта
/// </summary>
public abstract class AbstractStrategy
{
/// <summary>
/// Перемещаемый объект
/// </summary>
private IMoveableObject? _moveableObject;
/// <summary>
/// Статус перемещения
/// </summary>
private Status _state = Status.NotInit;
/// <summary>
/// Ширина поля
/// </summary>
protected int FieldWidth { get; private set; }
/// <summary>
/// Высота поля
/// </summary>
protected int FieldHeight { get; private set; }
/// <summary>
/// Статус перемещения
/// </summary>
public Status GetStatus() { return _state; }
/// <summary>
/// Установка данных
/// </summary>
/// <param name="moveableObject">Перемещаемый объект</param>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
public void SetData(IMoveableObject moveableObject, int width, int height)
{
if (moveableObject == null)
{
_state = Status.NotInit;
return;
}
_state = Status.InProgress;
_moveableObject = moveableObject;
FieldWidth = width;
FieldHeight = height;
}
/// <summary>
/// Шаг перемещения
/// </summary>
public void MakeStep()
{
if (_state != Status.InProgress)
{
return;
}
if (IsTargetDestinaion())
{
_state = Status.Finish;
return;
}
MoveToTarget();
}
/// <summary>
/// Перемещение влево
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false -
/// неудача)</returns>
protected bool MoveLeft() => MoveTo(Direction.Left);
/// <summary>
/// Перемещение вправо
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться,
///false - неудача)</returns>
protected bool MoveRight() => MoveTo(Direction.Right);
/// <summary>
/// Перемещение вверх
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться,
///false - неудача)</returns>
protected bool MoveUp() => MoveTo(Direction.Up);
/// <summary>
/// Перемещение вниз
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться,
///false - неудача)</returns>
protected bool MoveDown() => MoveTo(Direction.Down);
/// <summary>
/// Параметры объекта
/// </summary>
protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectPosition;
/// <summary>
/// Шаг объекта
/// </summary>
/// <returns></returns>
protected int? GetStep()
{
if (_state != Status.InProgress)
{
return null;
}
return _moveableObject?.GetStep;
}
/// <summary>
/// Перемещение к цели
/// </summary>
protected abstract void MoveToTarget();
/// <summary>
/// Достигнута ли цель
/// </summary>
/// <returns></returns>
protected abstract bool IsTargetDestinaion();
/// <summary>
/// Попытка перемещения в требуемом направлении
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>Результат попытки (true - удалось переместиться, false -
/// неудача)</returns>
private bool MoveTo(Direction direction)
{
if (_state != Status.InProgress)
{
return false;
}
if (_moveableObject?.CheckCanMove(direction) ?? false)
{
_moveableObject.MoveObject(direction);
return true;
}
return false;
}
}
}

View File

@ -1,40 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cruiser.Drawing;
namespace Cruiser.MovementStrategy
{
/// <summary>
/// Реализация интерфейса IDrawningObject для работы с объектом DrawningCar (паттерн Adapter)
/// </summary>
public class DrawningObjectCar : IMoveableObject
{
private readonly DrawingCruiser? _drawningCruiser = null;
public DrawningObjectCar(DrawingCruiser drawningCar)
{
_drawningCruiser = drawningCar;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_drawningCruiser == null || _drawningCruiser.EntityCruiser ==
null)
{
return null;
}
return new ObjectParameters(_drawningCruiser.GetPosX,
_drawningCruiser.GetPosY, _drawningCruiser.GetWidth, _drawningCruiser.GetHeight);
}
}
public int GetStep => (int)(_drawningCruiser?.EntityCruiser?.Step ?? 0);
public bool CheckCanMove(Direction direction) =>
_drawningCruiser?.CanMove(direction) ?? false;
public void MoveObject(Direction direction) =>
_drawningCruiser?.MoveTransport(direction);
}
}

View File

@ -1,31 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cruiser.Drawing;
namespace Cruiser.MovementStrategy
{
public interface IMoveableObject
{
/// <summary>
/// Получение координаты X объекта
/// </summary>
ObjectParameters? GetObjectPosition { get; }
/// <summary>
/// Шаг объекта
/// </summary>
int GetStep { get; }
/// <summary>
/// Проверка, можно ли переместиться по нужному направлению
/// </summary>
/// <param name="direction"></param>
/// <returns></returns>
bool CheckCanMove(Direction direction);
/// <summary>
/// Изменение направления пермещения объекта
/// </summary>
/// <param name="direction">Направление</param>
void MoveObject(Direction direction);
}
}

View File

@ -1,56 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cruiser.MovementStrategy
{
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.RightBorder <= FieldWidth &&
objParams.RightBorder + GetStep() >= FieldWidth &&
objParams.DownBorder <= FieldHeight &&
objParams.DownBorder + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
var diffX = objParams.RightBorder - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = objParams.DownBorder - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}
}

View File

@ -1,57 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cruiser.MovementStrategy
{
public class MoveToCenter : AbstractStrategy
{
protected override bool IsTargetDestinaion()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.ObjectMiddleHorizontal <= FieldWidth / 2 &&
objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2 &&
objParams.ObjectMiddleVertical <= FieldHeight / 2 &&
objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2;
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
var diffX = objParams.ObjectMiddleHorizontal - FieldWidth / 2;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
var diffY = objParams.ObjectMiddleVertical - FieldHeight / 2;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}
}

View File

@ -1,58 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cruiser.MovementStrategy
{
/// <summary>
/// Параметры-координаты объекта
/// </summary>
public class ObjectParameters
{
private readonly int _x;
private readonly int _y;
private readonly int _width;
private readonly int _height;
/// <summary>
/// Левая граница
/// </summary>
public int LeftBorder => _x;
/// <summary>
/// Верхняя граница
/// </summary>
public int TopBorder => _y;
/// <summary>
/// Правая граница
/// </summary>
public int RightBorder => _x + _width;
/// <summary>
/// Нижняя граница
/// </summary>
public int DownBorder => _y + _height;
/// <summary>
/// Середина объекта
/// </summary>
public int ObjectMiddleHorizontal => _x + _width / 2;
/// <summary>
/// Середина объекта
/// </summary>
public int ObjectMiddleVertical => _y + _height / 2;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
public ObjectParameters(int x, int y, int width, int height)
{
_x = x;
_y = y;
_width = width;
_height = height;
}
}
}

View File

@ -1,18 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cruiser.MovementStrategy
{
/// <summary>
/// Статус выполнения операции перемещения
/// </summary>
public enum Status
{
NotInit,
InProgress,
Finish
}
}

View File

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

View File

@ -1,103 +0,0 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Cruiser.Properties {
using System;
/// <summary>
/// Класс ресурса со строгой типизацией для поиска локализованных строк и т.д.
/// </summary>
// Этот класс создан автоматически классом StronglyTypedResourceBuilder
// с помощью такого средства, как ResGen или Visual Studio.
// Чтобы добавить или удалить член, измените файл .ResX и снова запустите ResGen
// с параметром /str или перестройте свой проект VS.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Возвращает кэшированный экземпляр ResourceManager, использованный этим классом.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Cruiser.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Перезаписывает свойство CurrentUICulture текущего потока для всех
/// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Down {
get {
object obj = ResourceManager.GetObject("Down", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Left {
get {
object obj = ResourceManager.GetObject("Left", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Right {
get {
object obj = ResourceManager.GetObject("Right", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Up {
get {
object obj = ResourceManager.GetObject("Up", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}

View File

@ -1,133 +0,0 @@
<?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>
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<data name="Left" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\resources\Left.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="Down" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\resources\Down.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="Up" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\resources\Up.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="Right" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\resources\Right.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
</root>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.5 KiB

View File

@ -1,31 +0,0 @@
private void Form1_Load(object sender, EventArgs e)
{
}
private void pictureBoxCruiser_Click(object sender, EventArgs e)
{
}
#region buttonsClick
private void buttonLeft_Click(object sender, EventArgs e)
{
}
private void buttonDown_Click(object sender, EventArgs e)
{
}
private void buttonUp_Click(object sender, EventArgs e)
{
}
private void buttonRight_Click(object sender, EventArgs e)
{
}
#endregion;