14 Commits
lab_3 ... lab_8

Author SHA1 Message Date
Alenka
72dcd86427 Done 2023-12-23 15:46:22 +04:00
Alenka
0f3e9f9a46 Done 2023-12-23 15:06:55 +04:00
Alenka
b6611a468c Done 2023-12-22 20:40:39 +04:00
Alenka
c4dca02f50 Начинать всегда стоит с того, что сеет сомнения 2023-12-22 20:33:02 +04:00
Alenka
bd31bcb20c Done 2023-12-08 22:08:43 +04:00
Alenka
03ebc0d612 Done 2023-12-08 21:45:56 +04:00
Alenka
ce753bc8db Done 2023-11-24 22:21:54 +04:00
Alenka
f0cb0ab565 Start 2023-11-24 20:01:41 +04:00
Alenka
c7f9f0fc86 Done 2023-11-17 21:18:59 +04:00
Alenka
36f18be18a done 2023-11-04 20:57:10 +04:00
Alenka
37aa57504d done 2023-11-04 17:53:47 +04:00
Alenka
315f4dda55 fix 2023-11-04 17:33:40 +04:00
Alenka
ca8833f4e1 Еще раз пофиксила 2023-10-28 16:31:55 +04:00
Alenka
9a5a57c959 Пофиксила 2023-10-28 00:25:29 +04:00
37 changed files with 1933 additions and 986 deletions

View File

@@ -1,42 +1,20 @@
using Cruiser; using Cruiser;
using DumpTruck.MovementStrategy; using Cruiser.MovementStrategy;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace Cruiser.MovementStrategy namespace Cruiser.MovementStrategy
{ {
public abstract class AbstractStrategy public abstract class AbstractStrategy
{ {
/// <summary>
/// Перемещаемый объект
/// </summary>
private IMoveableObject? _moveableObject; private IMoveableObject? _moveableObject;
/// <summary>
/// Статус перемещения
/// </summary>
private Status _state = Status.NotInit; private Status _state = Status.NotInit;
/// <summary>
/// Ширина поля
/// </summary>
protected int FieldWidth { get; private set; } protected int FieldWidth { get; private set; }
/// <summary>
/// Высота поля
/// </summary>
protected int FieldHeight { get; private set; } protected int FieldHeight { get; private set; }
/// <summary>
/// Статус перемещения
/// </summary>
public Status GetStatus() { return _state; } 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 public void SetData(IMoveableObject moveableObject, int width, int
height) height)
{ {
@@ -50,9 +28,6 @@ namespace Cruiser.MovementStrategy
FieldWidth = width; FieldWidth = width;
FieldHeight = height; FieldHeight = height;
} }
/// <summary>
/// Шаг перемещения
/// </summary>
public void MakeStep() public void MakeStep()
{ {
if (_state != Status.InProgress) if (_state != Status.InProgress)
@@ -66,35 +41,12 @@ namespace Cruiser.MovementStrategy
} }
MoveToTarget(); MoveToTarget();
} }
/// <summary> protected bool MoveLeft() => MoveTo(Direction.Left);
/// Перемещение влево protected bool MoveRight() => MoveTo(Direction.Right);
/// </summary> protected bool MoveUp() => MoveTo(Direction.Up);
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns> protected bool MoveDown() => MoveTo(Direction.Down);
protected bool MoveLeft() => MoveTo(DirectionType.Left);
/// <summary>
/// Перемещение вправо
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveRight() => MoveTo(DirectionType.Right);
/// <summary>
/// Перемещение вверх
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected bool MoveUp() => MoveTo(DirectionType.Up);
/// <summary>
/// Перемещение вниз
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться,false - неудача)</returns>
protected bool MoveDown() => MoveTo(DirectionType.Down);
/// <summary>
/// Параметры объекта
/// </summary>
protected ObjectParameters? GetObjectParameters => protected ObjectParameters? GetObjectParameters =>
_moveableObject?.GetObjectPosition; _moveableObject?.GetObjectPosition;
/// <summary>
/// Шаг объекта
/// </summary>
/// <returns></returns>
protected int? GetStep() protected int? GetStep()
{ {
if (_state != Status.InProgress) if (_state != Status.InProgress)
@@ -103,29 +55,17 @@ namespace Cruiser.MovementStrategy
} }
return _moveableObject?.GetStep; return _moveableObject?.GetStep;
} }
/// <summary>
/// Перемещение к цели
/// </summary>
protected abstract void MoveToTarget(); protected abstract void MoveToTarget();
/// <summary>
/// Достигнута ли цель
/// </summary>
/// <returns></returns>
protected abstract bool IsTargetDestinaion(); protected abstract bool IsTargetDestinaion();
/// <summary> private bool MoveTo(Direction direction)
/// Попытка перемещения в требуемом направлении
/// </summary>
/// <param name="directionType">Направление</param>
/// <returns>Результат попытки (true - удалось переместиться, false - неудача)</returns>
private bool MoveTo(DirectionType directionType)
{ {
if (_state != Status.InProgress) if (_state != Status.InProgress)
{ {
return false; return false;
} }
if (_moveableObject?.CheckCanMove(directionType) ?? false) if (_moveableObject?.CheckCanMove(direction) ?? false)
{ {
_moveableObject.MoveObject(directionType); _moveableObject.MoveObject(direction);
return true; return true;
} }
return false; return false;

View File

@@ -8,6 +8,18 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.7" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>

View File

@@ -0,0 +1,24 @@
using Cruiser.Generics;
namespace Cruiser
{
internal class CruiserCollectionInfo : IEquatable<CruiserCollectionInfo?>
{
public string Name { get; private set; }
public string Description { get; private set; }
public CruiserCollectionInfo(string name, string description)
{
Name = name;
Description = description;
}
public bool Equals(CruiserCollectionInfo? other)
{
if (other == null || other.Name == null)
throw new ArgumentNullException(nameof(other));
return Name == other.Name;
}
public override int GetHashCode()
{
return this.Name.GetHashCode();
}
}
}

View File

@@ -0,0 +1,32 @@
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cruiser.DrawningObjects;
using Cruiser.Entities;
namespace Cruiser.Generics
{
internal class CruiserCompareByColor : IComparer<DrawningCruiser>
{
public int Compare(DrawningCruiser? x, DrawningCruiser? y)
{
if (x == null || x.EntityCruiser == null)
throw new ArgumentNullException(nameof(x));
if (y == null || y.EntityCruiser == null)
throw new ArgumentNullException(nameof(y));
var xCruiser = x.EntityCruiser;
var yCruiser = y.EntityCruiser;
if (xCruiser.BodyColor != yCruiser.BodyColor)
return xCruiser.BodyColor.Name.CompareTo(yCruiser.BodyColor.Name);
var speedCompare = x.EntityCruiser.Speed.CompareTo(y.EntityCruiser.Speed);
if (speedCompare != 0)
return speedCompare;
return x.EntityCruiser.Weight.CompareTo(y.EntityCruiser.Weight);
}
}
}

View File

@@ -0,0 +1,28 @@
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cruiser.DrawningObjects;
namespace Cruiser.Generics
{
internal class CruiserCompareByType : IComparer<DrawningCruiser>
{
public int Compare(DrawningCruiser? x, DrawningCruiser? y)
{
if (x == null || x.EntityCruiser == null)
throw new ArgumentNullException(nameof(x));
if (y == null || y.EntityCruiser == null)
throw new ArgumentNullException(nameof(y));
if (x.GetType().Name != y.GetType().Name)
return x.GetType().Name.CompareTo(y.GetType().Name);
var speedCompare = x.EntityCruiser.Speed.CompareTo(y.EntityCruiser.Speed);
if (speedCompare != 0)
return speedCompare;
return x.EntityCruiser.Weight.CompareTo(y.EntityCruiser.Weight);
}
}
}

167
Cruiser/Cruiser/CruiserForm.Designer.cs generated Normal file
View File

@@ -0,0 +1,167 @@
namespace Cruiser
{
partial class CruiserForm
{
private System.ComponentModel.IContainer components = null;
#region Windows Form Designer generated code
private void InitializeComponent()
{
this.pictureBoxCruiser = new System.Windows.Forms.PictureBox();
this.ButtonDown = new System.Windows.Forms.Button();
this.ButtonLeft = new System.Windows.Forms.Button();
this.ButtonRight = new System.Windows.Forms.Button();
this.ButtonUp = new System.Windows.Forms.Button();
this.buttonAdvancedCreate = new System.Windows.Forms.Button();
this.buttonCreate = new System.Windows.Forms.Button();
this.comboBoxCruiser = new System.Windows.Forms.ComboBox();
this.ButtonStep = new System.Windows.Forms.Button();
this.ButtonSelected = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCruiser)).BeginInit();
this.SuspendLayout();
//
// pictureBoxCruiser
//
this.pictureBoxCruiser.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBoxCruiser.Location = new System.Drawing.Point(0, 0);
this.pictureBoxCruiser.Name = "pictureBoxCruiser";
this.pictureBoxCruiser.Size = new System.Drawing.Size(667, 358);
this.pictureBoxCruiser.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pictureBoxCruiser.TabIndex = 0;
this.pictureBoxCruiser.TabStop = false;
this.pictureBoxCruiser.Click += new System.EventHandler(this.ButtonMove_Click);
//
// ButtonDown
//
this.ButtonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.ButtonDown.BackgroundImage = global::Cruiser.Properties.Resources.вниз;
this.ButtonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.ButtonDown.Location = new System.Drawing.Point(543, 306);
this.ButtonDown.Name = "ButtonDown";
this.ButtonDown.Size = new System.Drawing.Size(30, 30);
this.ButtonDown.TabIndex = 1;
this.ButtonDown.UseVisualStyleBackColor = true;
this.ButtonDown.Click += new System.EventHandler(this.ButtonMove_Click);
//
// ButtonLeft
//
this.ButtonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.ButtonLeft.BackgroundImage = global::Cruiser.Properties.Resources.влево;
this.ButtonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.ButtonLeft.Location = new System.Drawing.Point(517, 306);
this.ButtonLeft.Name = "ButtonLeft";
this.ButtonLeft.Size = new System.Drawing.Size(30, 30);
this.ButtonLeft.TabIndex = 2;
this.ButtonLeft.UseVisualStyleBackColor = true;
this.ButtonLeft.Click += new System.EventHandler(this.ButtonMove_Click);
//
// ButtonRight
//
this.ButtonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.ButtonRight.BackgroundImage = global::Cruiser.Properties.Resources.вправо;
this.ButtonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.ButtonRight.Location = new System.Drawing.Point(567, 306);
this.ButtonRight.Name = "ButtonRight";
this.ButtonRight.Size = new System.Drawing.Size(30, 30);
this.ButtonRight.TabIndex = 3;
this.ButtonRight.UseVisualStyleBackColor = true;
this.ButtonRight.Click += new System.EventHandler(this.ButtonMove_Click);
//
// ButtonUp
//
this.ButtonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.ButtonUp.BackgroundImage = global::Cruiser.Properties.Resources.вверх;
this.ButtonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.ButtonUp.Location = new System.Drawing.Point(543, 284);
this.ButtonUp.Name = "ButtonUp";
this.ButtonUp.Size = new System.Drawing.Size(30, 30);
this.ButtonUp.TabIndex = 4;
this.ButtonUp.UseVisualStyleBackColor = true;
this.ButtonUp.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonAdvancedCreate
//
this.buttonAdvancedCreate.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonAdvancedCreate.Location = new System.Drawing.Point(12, 267);
this.buttonAdvancedCreate.Name = "buttonAdvancedCreate";
this.buttonAdvancedCreate.Size = new System.Drawing.Size(210, 69);
this.buttonAdvancedCreate.TabIndex = 5;
this.buttonAdvancedCreate.Text = "Создать продвинутую версию";
this.buttonAdvancedCreate.UseVisualStyleBackColor = true;
this.buttonAdvancedCreate.Click += new System.EventHandler(this.ButtonAdvancedCreate_Click);
//
// buttonCreate
//
this.buttonCreate.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonCreate.Location = new System.Drawing.Point(240, 267);
this.buttonCreate.Name = "buttonCreate";
this.buttonCreate.Size = new System.Drawing.Size(242, 69);
this.buttonCreate.TabIndex = 6;
this.buttonCreate.Text = "Создать простую версию";
this.buttonCreate.UseVisualStyleBackColor = true;
this.buttonCreate.Click += new System.EventHandler(this.ButtonCreate_Click);
//
// comboBoxCruiser
//
this.comboBoxCruiser.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxCruiser.FormattingEnabled = true;
this.comboBoxCruiser.Items.AddRange(new object[] {
"Центр",
"Угол"});
this.comboBoxCruiser.Location = new System.Drawing.Point(415, 22);
this.comboBoxCruiser.Name = "comboBoxCruiser";
this.comboBoxCruiser.Size = new System.Drawing.Size(182, 33);
this.comboBoxCruiser.TabIndex = 7;
//
// ButtonStep
//
this.ButtonStep.Location = new System.Drawing.Point(485, 70);
this.ButtonStep.Name = "ButtonStep";
this.ButtonStep.Size = new System.Drawing.Size(112, 34);
this.ButtonStep.TabIndex = 8;
this.ButtonStep.Text = "Шаг";
this.ButtonStep.UseVisualStyleBackColor = true;
this.ButtonStep.Click += new System.EventHandler(this.ButtonStep_Click);
//
// ButtonSelected
//
this.ButtonSelected.Location = new System.Drawing.Point(180, 215);
this.ButtonSelected.Name = "ButtonSelected";
this.ButtonSelected.Size = new System.Drawing.Size(105, 34);
this.ButtonSelected.TabIndex = 9;
this.ButtonSelected.Text = "Выбрать";
this.ButtonSelected.UseVisualStyleBackColor = true;
this.ButtonSelected.Click += new System.EventHandler(this.ButtonSelectedCruiser_Click);
//
// CruiserForm
//
this.ClientSize = new System.Drawing.Size(667, 358);
this.Controls.Add(this.ButtonSelected);
this.Controls.Add(this.ButtonStep);
this.Controls.Add(this.comboBoxCruiser);
this.Controls.Add(this.buttonCreate);
this.Controls.Add(this.buttonAdvancedCreate);
this.Controls.Add(this.ButtonUp);
this.Controls.Add(this.ButtonRight);
this.Controls.Add(this.ButtonLeft);
this.Controls.Add(this.ButtonDown);
this.Controls.Add(this.pictureBoxCruiser);
this.Name = "CruiserForm";
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCruiser)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private PictureBox pictureBoxCruiser;
private Button ButtonDown;
private Button ButtonLeft;
private Button ButtonRight;
private Button ButtonUp;
private Button buttonAdvancedCreate;
private Button buttonCreate;
private ComboBox comboBoxCruiser;
private Button ButtonStep;
private Button ButtonSelected;
}
}

View File

@@ -0,0 +1,135 @@
using System.Windows.Forms;
using Cruiser.DrawningObjects;
using Cruiser.MovementStrategy;
namespace Cruiser
{
public partial class CruiserForm : Form
{
private DrawningCruiser? _drawningCruiser;
private AbstractStrategy? _abstractStrategy;
public DrawningCruiser? SelectedCruiser { get; private set; }
public CruiserForm()
{
InitializeComponent();
_abstractStrategy = null;
SelectedCruiser = null;
}
private void Draw()
{
if (_drawningCruiser == null)
{
return;
}
Bitmap bmp = new Bitmap(pictureBoxCruiser.Width, pictureBoxCruiser.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningCruiser.DrawTransport(gr);
pictureBoxCruiser.Image = bmp;
}
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();
}
private void ButtonCreate_Click(object sender, EventArgs e)
{
Random random = new();
Color color = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
ColorDialog dialogColor = new();
if (dialogColor.ShowDialog() == DialogResult.OK)
{
color = dialogColor.Color;
}
_drawningCruiser = new DrawningCruiser(random.Next(100, 300), random.Next(1000, 3000),
color, pictureBoxCruiser.Width, pictureBoxCruiser.Height);
_drawningCruiser.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
private void ButtonStep_Click(object sender, EventArgs e)
{
if (_drawningCruiser == null)
{
return;
}
if (comboBoxCruiser.Enabled)
{
_abstractStrategy = comboBoxCruiser.SelectedIndex
switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(new DrawningObjectCruiser(_drawningCruiser), pictureBoxCruiser.Width,
pictureBoxCruiser.Height);
}
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBoxCruiser.Enabled = true;
_abstractStrategy = null;
}
}
private void ButtonAdvancedCreate_Click(object sender, EventArgs e)
{
Random random = new();
Color color = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
ColorDialog dialogColor = new();
if (dialogColor.ShowDialog() == DialogResult.OK)
{
color = dialogColor.Color;
}
Color dopColor = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
ColorDialog dialogDopColor = new();
if (dialogDopColor.ShowDialog() == DialogResult.OK)
{
dopColor = dialogDopColor.Color;
}
_drawningCruiser = new DrawningAdvancedCruiser(random.Next(100, 300),
random.Next(1000, 3000), color, dopColor, Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)),
pictureBoxCruiser.Width, pictureBoxCruiser.Height);
_drawningCruiser.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
private void ButtonSelectedCruiser_Click(object sender, EventArgs e)
{
SelectedCruiser = _drawningCruiser;
DialogResult = DialogResult.OK;
}
}
}

View File

@@ -4,42 +4,23 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Cruiser.Generics; using Cruiser.Generics;
using Cruiser.DrawningObjects; using Cruiser.DrawningObjects;
using Cruiser.Entities; using Cruiser.Entities;
using Cruiser.MovementStrategy; using Cruiser.MovementStrategy;
namespace DumpTruck.Generics namespace Cruiser.Generics
{ {
internal class CruiserGenericCollection<T, U> internal class CruiserGenericCollection<T, U>
where T : DrawningCar
where T : DrawningCruiser
where U : IMoveableObject where U : IMoveableObject
{ {
/// <summary>
/// Ширина окна прорисовки
/// </summary>
private readonly int _pictureWidth; private readonly int _pictureWidth;
/// <summary>
/// Высота окна прорисовки
/// </summary>
private readonly int _pictureHeight; private readonly int _pictureHeight;
/// <summary> private readonly int _placeSizeWidth = 170;
/// Размер занимаемого объектом места (ширина) private readonly int _placeSizeHeight = 200;
/// </summary>
private readonly int _placeSizeWidth = 210;
/// <summary>
/// Размер занимаемого объектом места (высота)
/// </summary>
private readonly int _placeSizeHeight = 90;
/// <summary>
/// Набор объектов
/// </summary>
private readonly SetGeneric<T> _collection; private readonly SetGeneric<T> _collection;
/// <summary> public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
public CruiserGenericCollection(int picWidth, int picHeight) public CruiserGenericCollection(int picWidth, int picHeight)
{ {
int width = picWidth / _placeSizeWidth; int width = picWidth / _placeSizeWidth;
@@ -48,51 +29,24 @@ namespace DumpTruck.Generics
_pictureHeight = picHeight; _pictureHeight = picHeight;
_collection = new SetGeneric<T>(width * height); _collection = new SetGeneric<T>(width * height);
} }
/// <summary> public static bool operator +(CruiserGenericCollection<T, U>? collect, T? obj)
/// Перегрузка оператора сложения
/// </summary>
/// <param name="collect"></param>
/// <param name="obj"></param>
/// <returns></returns>
public static int operator +(CruiserGenericCollection<T, U> collect, T?
obj)
{ {
if (obj == null) if (obj == null || collect == null)
{ return false;
return -1; collect?._collection.Insert(obj, new DrawningCruiserEqutables());
}
return collect._collection.Insert(obj) ;
}
/// <summary>
/// Перегрузка оператора вычитания
/// </summary>
/// <param name="collect"></param>
/// <param name="pos"></param>
/// <returns></returns>
public static bool operator -(CruiserGenericCollection<T, U> collect, int
pos)
{
T? obj = collect._collection.Get(pos);
if (obj != null)
{
collect._collection.Remove(pos);
}
return true; return true;
} }
/// <summary> public static T? operator -(CruiserGenericCollection<T, U> collect, int pos)
/// Получение объекта IMoveableObject {
/// </summary> T? obj = collect._collection[pos];
/// <param name="pos"></param> collect._collection.Remove(pos);
/// <returns></returns> return obj;
}
public U? GetU(int pos) public U? GetU(int pos)
{ {
return (U?)_collection.Get(pos)?.GetMoveableObject; return (U?)_collection[pos]?.GetMoveableObject;
} }
/// <summary> public Bitmap ShowCruisers()
/// Вывод всего набора объектов
/// </summary>
/// <returns></returns>
public Bitmap ShowCars()
{ {
Bitmap bmp = new(_pictureWidth, _pictureHeight); Bitmap bmp = new(_pictureWidth, _pictureHeight);
Graphics gr = Graphics.FromImage(bmp); Graphics gr = Graphics.FromImage(bmp);
@@ -100,10 +54,6 @@ namespace DumpTruck.Generics
DrawObjects(gr); DrawObjects(gr);
return bmp; return bmp;
} }
/// <summary>
/// Метод отрисовки фона
/// </summary>
/// <param name="g"></param>
private void DrawBackground(Graphics g) private void DrawBackground(Graphics g)
{ {
Pen pen = new(Color.Black, 3); Pen pen = new(Color.Black, 3);
@@ -111,7 +61,7 @@ namespace DumpTruck.Generics
{ {
for (int j = 0; j < _pictureHeight / _placeSizeHeight + for (int j = 0; j < _pictureHeight / _placeSizeHeight +
1; ++j) 1; ++j)
{//линия рамзетки места {
g.DrawLine(pen, i * _placeSizeWidth, j * g.DrawLine(pen, i * _placeSizeWidth, j *
_placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth / 2, j * _placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth / 2, j *
_placeSizeHeight); _placeSizeHeight);
@@ -120,28 +70,20 @@ namespace DumpTruck.Generics
_placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight); _placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight);
} }
} }
/// <summary>
/// Метод прорисовки объектов
/// </summary>
/// <param name="g"></param>
private void DrawObjects(Graphics g) private void DrawObjects(Graphics g)
{ {
DrawningCar car; int i = 0;
int numPlacesInRow = _pictureWidth / _placeSizeWidth; foreach (var cruiser in _collection.GetCruiser())
for (int i = 0; i < _collection.Count; i++)
{ {
// TODO получение объекта if (cruiser != null)
// TODO установка позиции
// TODO прорисовка объекта
car = _collection.Get(i);
if (car != null)
{ {
car.SetPosition((i % numPlacesInRow) * _placeSizeWidth + _placeSizeWidth / 20, _placeSizeHeight * (i / numPlacesInRow) + _placeSizeHeight / 10); int inRow = _pictureWidth / _placeSizeWidth;
//car.SetPosition(_placeSizeWidth * (i/ numPlacesInColumn) + _placeSizeWidth / 20, (i % numPlacesInColumn ) *_placeSizeHeight + _placeSizeHeight / 10); cruiser.SetPosition(_pictureWidth - _placeSizeWidth - (i % inRow * _placeSizeWidth) - _placeSizeHeight / 2 - 8, i / inRow * _placeSizeHeight + 20);
car.DrawTransport(g); cruiser.DrawTransport(g);
} }
i++;
} }
} }
public IEnumerable<T?> GetCruisers => _collection.GetCruiser();
} }
} }

View File

@@ -0,0 +1,124 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cruiser.DrawningObjects;
using Cruiser.MovementStrategy;
namespace Cruiser.Generics
{
internal class CruiserGenericStorage
{
readonly Dictionary<CruiserCollectionInfo, CruiserGenericCollection<DrawningCruiser,
DrawningObjectCruiser>> _cruiserStorages;
public List<CruiserCollectionInfo> Keys => _cruiserStorages.Keys.ToList();
private readonly int _pictureWidth;
private readonly int _pictureHeight;
private static readonly char _separatorForKeyValue = '|';
private readonly char _separatorRecords = ';';
private static readonly char _separatorForObject = ':';
public CruiserGenericStorage(int pictureWidth, int pictureHeight)
{
_cruiserStorages = new Dictionary<CruiserCollectionInfo, CruiserGenericCollection<DrawningCruiser, DrawningObjectCruiser>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
public void AddSet(string name)
{
_cruiserStorages.Add(new CruiserCollectionInfo(name, string.Empty), new CruiserGenericCollection<DrawningCruiser, DrawningObjectCruiser>(_pictureWidth, _pictureHeight));
}
public void DelSet(string name)
{
if (!_cruiserStorages.ContainsKey(new CruiserCollectionInfo(name, string.Empty)));
{
return;
}
_cruiserStorages.Remove(new CruiserCollectionInfo(name, string.Empty));
}
public CruiserGenericCollection<DrawningCruiser, DrawningObjectCruiser>? this[string ind]
{
get
{
CruiserCollectionInfo indObj = new CruiserCollectionInfo(ind, string.Empty);
if (_cruiserStorages.ContainsKey(indObj))
return _cruiserStorages[indObj];
return null;
}
}
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<CruiserCollectionInfo, CruiserGenericCollection<DrawningCruiser, DrawningObjectCruiser>> record in _cruiserStorages)
{
StringBuilder records = new();
foreach (DrawningCruiser? elem in record.Value.GetCruisers)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key.Name}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
throw new Exception("Невалидная операция, нет данных для сохранения");
}
using (StreamWriter sw = new(filename))
{
sw.WriteLine($"PlaneStorage{Environment.NewLine}{data}");
}
return;
}
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new IOException("Файл не найден");
}
using (StreamReader sr = new(filename))
{
string str = sr.ReadLine();
var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
throw new IOException("Нет данных для загрузки");
}
if (!strs[0].StartsWith("PlaneStorage"))
{
throw new IOException("Неверный формат данных");
}
_cruiserStorages.Clear();
do
{
string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
str = sr.ReadLine();
continue;
}
CruiserGenericCollection<DrawningCruiser, DrawningObjectCruiser> collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords,
StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawningCruiser? cruiser = elem?.CreateDrawningCruiser(_separatorForObject, _pictureWidth, _pictureHeight);
if (cruiser != null)
{
if (!(collection + cruiser))
{
throw new ArgumentNullException("Ошибка добавления в коллекцию");
}
}
}
_cruiserStorages.Add(new CruiserCollectionInfo(record[0], string.Empty), collection);
str = sr.ReadLine();
} while (str != null);
}
return;
}
}
}

View File

@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace Cruiser.Exceptions
{
[Serializable]
internal class CruiserNotFoundException : ApplicationException
{
public CruiserNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
public CruiserNotFoundException() : base() { }
public CruiserNotFoundException(string message) : base(message) { }
public CruiserNotFoundException(string message, Exception exception) : base(message, exception) { }
protected CruiserNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

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

View File

@@ -1,5 +1,4 @@
using DumpTruck; using System;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Drawing; using System.Drawing;
using System.Linq; using System.Linq;
@@ -9,52 +8,51 @@ using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using Cruiser.Entities; using Cruiser.Entities;
namespace Cruiser.DrawningObjects namespace Cruiser.DrawningObjects
{ {
public class DrawningDumpTruck : DrawningCar public class DrawningAdvancedCruiser : DrawningCruiser
{ {
public DrawningAdvancedCruiser(int speed, double weight, Color bodyColor, Color additionalColor, bool helicopterPad, bool coating, int width, int height) : base(speed, weight, bodyColor, width, height, 110, 60)
public DrawningDumpTruck(int speed, double weight, Color bodyColor, Color additionalColor, bool bodyKit, bool tent, int width, int height) : base(speed, weight, bodyColor, width, height, 110, 60)
{ {
if (EntityCar != null) if (EntityCruiser != null)
{ {
EntityCar = new EntityAdvancedCruiser(speed, weight, bodyColor, additionalColor, bodyKit, tent); EntityCruiser = new EntityAdvancedCruiser(speed, weight, bodyColor, additionalColor, helicopterPad, coating);
} }
} }
public override void DrawTransport(Graphics g) public override void DrawTransport(Graphics g)
{ {
if (EntityCar is not EntityAdvancedCruiser dumpTruck) if (EntityCruiser is not EntityAdvancedCruiser cruiser)
{ {
return; return;
} }
Brush addBrush = new SolidBrush(cruiser.AdditionalColor);
Pen pen = new Pen(Color.Black);
Brush addBrush = new SolidBrush(dumpTruck.AdditionalColor);
Brush brush = new SolidBrush(dumpTruck.BodyColor);
base.DrawTransport(g); base.DrawTransport(g);
if (dumpTruck.Tent) if (cruiser.HelicopterPad)
{ {
Brush brYellow = new SolidBrush(Color.Yellow);
g.FillEllipse(brYellow, _startPosX + 80, _startPosY + 5, 20,
20);
g.FillEllipse(brYellow, _startPosX + 80, _startPosY + 35, 20,
20);
}
if (dumpTruck.BodyKit) Point[] trianglePoints1 =
{
new Point(_startPosX + 20, _startPosY + 5),
new Point(_startPosX + 40, _startPosY + 25),
new Point(_startPosX + 60, _startPosY + 5)
};
Point[] trianglePoints2 =
{
new Point(_startPosX + 20, _startPosY + 55),
new Point(_startPosX + 40, _startPosY + 35),
new Point(_startPosX + 60, _startPosY + 55)
};
g.FillPolygon(addBrush, trianglePoints1);
g.FillPolygon(addBrush, trianglePoints2);
}
if (cruiser.Coating)
{ {
g.FillEllipse(Brushes.Green, _startPosX + 90, _startPosY + 20, 20, 20); g.FillEllipse(addBrush, _startPosX + 90, _startPosY + 20, 20, 20);
}
} }
} }
} }
}

View File

@@ -3,202 +3,134 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Cruiser.Entities; using Cruiser.Entities;
using Cruiser.MovementStrategy; using Cruiser.MovementStrategy;
using Cruiser;
namespace Cruiser.DrawningObjects namespace Cruiser.DrawningObjects
{ {
public class DrawningCruiser public class DrawningCruiser
{ {
public EntityCruiser? EntityCar { get; protected set; } public EntityCruiser? EntityCruiser { get; protected set; }
private int _pictureWidth; private int _pictureWidth;
private int _pictureHeight; private int _pictureHeight;
protected int _startPosX; protected int _startPosX;
protected int _startPosY; protected int _startPosY;
private readonly int _cruiserWidth = 110;
private readonly int _carWidth = 110; private readonly int _cruiserHeight = 60;
private readonly int _carHeight = 60;
/// <summary>
/// Координата X объекта
/// </summary>
public int GetPosX => _startPosX; public int GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int GetPosY => _startPosY; public int GetPosY => _startPosY;
/// <summary> public int GetWidth => _cruiserWidth;
/// Ширина объекта public int GetHeight => _cruiserHeight;
/// </summary>
public int GetWidth => _carWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _carHeight;
/// <summary>
/// Получение объекта IMoveableObject из объекта DrawningCar
/// </summary>
public IMoveableObject GetMoveableObject => new DrawningObjectCruiser(this); public IMoveableObject GetMoveableObject => new DrawningObjectCruiser(this);
public DrawningCruiser(int speed, double weight, Color bodyColor, int width, int height) public DrawningCruiser(int speed, double weight, Color bodyColor, int width, int height)
{ {
if (width < _carWidth || height < _carHeight) if (width < _cruiserWidth || height < _cruiserHeight)
{ {
return; return;
} }
_pictureWidth = width; _pictureWidth = width;
_pictureHeight = height; _pictureHeight = height;
EntityCruiser = new EntityCruiser(speed, weight, bodyColor);
EntityCar = new EntityCruiser(speed, weight, bodyColor);
} }
protected DrawningCruiser(int speed, double weight, Color bodyColor, int protected DrawningCruiser(int speed, double weight, Color bodyColor, int
width, int height, int carWidth, int carHeight) width, int height, int cruiserWidth, int cruiserHeight)
{ {
if (width <= _carWidth || height <= _carHeight) if (width <= _cruiserWidth || height <= _cruiserHeight)
{ {
return; return;
} }
_pictureWidth = width; _pictureWidth = width;
_pictureHeight = height; _pictureHeight = height;
_carWidth = carWidth; _cruiserWidth = cruiserWidth;
_carHeight = carHeight; _cruiserHeight = cruiserHeight;
EntityCar = new EntityCruiser(speed, weight, bodyColor); EntityCruiser = new EntityCruiser(speed, weight, bodyColor);
} }
public void SetPosition(int x, int y) public void SetPosition(int x, int y)
{ {
if (x < 0 || x >= _pictureWidth || y < 0 || y >= _pictureHeight) if (x < 0 || x + _cruiserWidth > _pictureWidth)
{ {
_startPosX = 0; x = Math.Max(0, _pictureWidth - _cruiserWidth);
_startPosY = 0; }
if (y < 0 || y + _cruiserHeight > _pictureHeight)
{
y = Math.Max(0, _pictureHeight - _cruiserHeight);
} }
_startPosX = x; _startPosX = x;
_startPosY = y; _startPosY = y;
} }
public void MoveTransport(Direction direction)
public void MoveTransport(DirectionType direction)
{ {
if (!CanMove(direction) || EntityCar == null) if (!CanMove(direction) || EntityCruiser == null)
{ {
return; return;
} }
switch (direction) switch (direction)
{ {
//влево case Direction.Left:
case DirectionType.Left: _startPosX -= (int)EntityCruiser.Step;
_startPosX -= (int)EntityCar.Step;
break; break;
//вверх case Direction.Up:
case DirectionType.Up: _startPosY -= (int)EntityCruiser.Step;
_startPosY -= (int)EntityCar.Step;
break; break;
// вправо case Direction.Right:
case DirectionType.Right: _startPosX += (int)EntityCruiser.Step;
_startPosX += (int)EntityCar.Step;
break; break;
//вниз case Direction.Down:
case DirectionType.Down: _startPosY += (int)EntityCruiser.Step;
_startPosY += (int)EntityCar.Step;
break; break;
} }
} }
public bool CanMove(Direction direction)
public bool CanMove(DirectionType direction)
{ {
if (EntityCar == null) if (EntityCruiser == null)
{ {
return false; return false;
} }
return direction switch return direction switch
{ {
//влево Direction.Left => _startPosX - EntityCruiser.Step > 0,
DirectionType.Left => _startPosX - EntityCar.Step > 0, Direction.Up => _startPosY - EntityCruiser.Step > 0,
//вверх Direction.Right => _startPosX + EntityCruiser.Step + _cruiserWidth < _pictureWidth,
DirectionType.Up => _startPosY - EntityCar.Step > 0, Direction.Down => _startPosY + EntityCruiser.Step + _cruiserHeight < _pictureHeight,
// вправо
DirectionType.Right => _startPosX + EntityCar.Step + _carWidth < _pictureWidth,
//вниз
DirectionType.Down => _startPosY + EntityCar.Step + _carHeight < _pictureHeight,
_ => false, _ => false,
}; };
} }
public void ChangePictureBoxSize(int pictureBoxWidth, int pictureBoxHeight)
{
_pictureWidth = pictureBoxWidth;
_pictureHeight = pictureBoxHeight;
}
public virtual void DrawTransport(Graphics g) public virtual void DrawTransport(Graphics g)
{ {
if (EntityCar == null) if (EntityCruiser == null)
{ {
return; return;
} }
Pen pen = new Pen(Color.Black); Pen pen = new Pen(Color.Black);
Brush brush = new SolidBrush(EntityCar.BodyColor); Brush brush = new SolidBrush(EntityCruiser.BodyColor);
//границы автомобиля
//SolidBrush(Cruiser.AdditionalColor);
//границы автомобиля
g.DrawEllipse(pen, _startPosX + 15, _startPosY + 5, 20, 20); g.DrawEllipse(pen, _startPosX + 15, _startPosY + 5, 20, 20);
g.DrawEllipse(pen, _startPosX + 15, _startPosY + 35, 20, 20); g.DrawEllipse(pen, _startPosX + 15, _startPosY + 35, 20, 20);
g.DrawRectangle(pen, _startPosX + 9, _startPosY + 15, 10, 30); g.DrawRectangle(pen, _startPosX + 9, _startPosY + 15, 10, 30);
g.DrawRectangle(pen, _startPosX + 90, _startPosY + 15, 10, g.DrawRectangle(pen, _startPosX + 90, _startPosY + 15, 10,
30); 30);
g.DrawRectangle(pen, _startPosX + 20, _startPosY + 4, 70, 52); g.DrawRectangle(pen, _startPosX + 20, _startPosY + 4, 70, 52);
Brush br = new SolidBrush(EntityCruiser.BodyColor);
//если есть доп.фонари
/* if (Cruiser.Headlights)
{
Brush brYellow = new SolidBrush(Color.Yellow);
g.FillEllipse(brYellow, _startPosX + 80, _startPosY + 5, 20,
20);
g.FillEllipse(brYellow, _startPosX + 80, _startPosY + 35, 20,
20);
}*/
//основание лодки!!!
Brush br = new SolidBrush(EntityCar.BodyColor);
g.FillRectangle(br, _startPosX + 10, _startPosY + 15, 10, 30); g.FillRectangle(br, _startPosX + 10, _startPosY + 15, 10, 30);
g.FillRectangle(br, _startPosX + 90, _startPosY + 15, 10, 30); g.FillRectangle(br, _startPosX + 90, _startPosY + 15, 10, 30);
g.FillRectangle(br, _startPosX + 20, _startPosY + 5, 70, 50); g.FillRectangle(br, _startPosX + 20, _startPosY + 5, 70, 50);
Point[] points = new Point[3];// нос лодки Point[] points = new Point[3];//
points[0] = new Point(_startPosX + 100, _startPosY + 5); points[0] = new Point(_startPosX + 100, _startPosY + 5);
points[1] = new Point(_startPosX + 100, _startPosY + 55); points[1] = new Point(_startPosX + 100, _startPosY + 55);
points[2] = new Point(_startPosX + 100 + 50, _startPosY + 50 / 2); points[2] = new Point(_startPosX + 100 + 50, _startPosY + 50 / 2);
g.FillPolygon(Brushes.Pink, points); g.FillPolygon(Brushes.Pink, points);
//границы носа лодки
Point[] points1 = new Point[3];// нос лодки
points1[0] = new Point(_startPosX + 100, _startPosY + 5);
points1[1] = new Point(_startPosX + 100, _startPosY + 55);
points1[2] = new Point(_startPosX + 100 + 50, _startPosY + 50 / 2);
g.DrawPolygon(pen, points1);
g.FillRectangle(Brushes.Black, _startPosX + 5, _startPosY + 15, 10, 10); g.FillRectangle(Brushes.Black, _startPosX + 5, _startPosY + 15, 10, 10);
g.FillRectangle(Brushes.Black, _startPosX + 5, _startPosY + 35, 10, 10); g.FillRectangle(Brushes.Black, _startPosX + 5, _startPosY + 35, 10, 10);
//если есть ракетные шахты, добавить условие
g.DrawRectangle(Pens.Black, _startPosX + 35, g.DrawRectangle(Pens.Black, _startPosX + 35,
_startPosY + 23, 15, 15); _startPosY + 23, 15, 15);
g.DrawRectangle(Pens.Black, _startPosX + 50, g.DrawRectangle(Pens.Black, _startPosX + 50,
_startPosY + 19, 30, 25); _startPosY + 19, 30, 25);
} }
} }
} }

View File

@@ -0,0 +1,57 @@
using Cruiser.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cruiser.DrawningObjects;
namespace Cruiser
{
internal class DrawingCruiserEqutables : IEqualityComparer<DrawningCruiser?>
{
public bool Equals(DrawningCruiser? x, DrawningCruiser? y)
{
if (x == null || x.EntityCruiser == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityCruiser == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityCruiser.Speed != y.EntityCruiser.Speed)
{
return false;
}
if (x.EntityCruiser.Weight != y.EntityCruiser.Weight)
{
return false;
}
if (x.EntityCruiser.BodyColor != y.EntityCruiser.BodyColor)
{
return false;
}
if (x is DrawningAdvancedCruiser && y is DrawningAdvancedCruiser)
{
EntityAdvancedCruiser EntityX = (EntityAdvancedCruiser)x.EntityCruiser;
EntityAdvancedCruiser EntityY = (EntityAdvancedCruiser)y.EntityCruiser;
if (EntityX.HelicopterPad != EntityY.HelicopterPad)
return false;
if (EntityX.Coating != EntityY.Coating)
return false;
if (EntityX.AdditionalColor != EntityY.AdditionalColor)
return false;
}
return true;
}
public int GetHashCode([DisallowNull] DrawningCruiser? obj)
{
return obj.GetHashCode();
}
}
}

View File

@@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cruiser.DrawningObjects;
using Cruiser.Entities;
namespace Cruiser
{
internal class DrawningCruiserEqutables : IEqualityComparer<DrawningCruiser?>
{
public bool Equals(DrawningCruiser? x, DrawningCruiser? y)
{
if (x == null || x.EntityCruiser == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.EntityCruiser == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityCruiser.Speed != y.EntityCruiser.Speed)
{
return false;
}
if (x.EntityCruiser.Weight != y.EntityCruiser.Weight)
{
return false;
}
if (x.EntityCruiser.BodyColor != y.EntityCruiser.BodyColor)
{
return false;
}
if (x is DrawningAdvancedCruiser && y is DrawningAdvancedCruiser)
{
EntityAdvancedCruiser EntityX = (EntityAdvancedCruiser)x.EntityCruiser;
EntityAdvancedCruiser EntityY = (EntityAdvancedCruiser)y.EntityCruiser;
if (EntityX.HelicopterPad != EntityY.HelicopterPad)
return false;
if (EntityX.Coating != EntityY.Coating)
return false;
if (EntityX.AdditionalColor != EntityY.AdditionalColor)
return false;
}
return true;
}
public int GetHashCode([DisallowNull] DrawningCruiser? obj)
{
return obj.GetHashCode();
}
}
}

View File

@@ -3,37 +3,33 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Cruiser;
using Cruiser.DrawningObjects; using Cruiser.DrawningObjects;
namespace Cruiser.MovementStrategy namespace Cruiser.MovementStrategy
{ {
internal class DrawningObjectCruiser : IMoveableObject internal class DrawningObjectCruiser : IMoveableObject
{ {
private readonly DrawningCruiser? _drawningCar = null; private readonly DrawningCruiser? _drawningCruiser = null;
public DrawningObjectCruiser(DrawningCruiser drawningCruiser) public DrawningObjectCruiser(DrawningCruiser drawningCruiser)
{ {
_drawningCar = drawningCruiser; _drawningCruiser = drawningCruiser;
} }
public ObjectParameters? GetObjectPosition public ObjectParameters? GetObjectPosition
{ {
get get
{ {
if (_drawningCar == null || _drawningCar.EntityCar == if (_drawningCruiser == null || _drawningCruiser.EntityCruiser ==
null) null)
{ {
return null; return null;
} }
return new ObjectParameters(_drawningCar.GetPosX, return new ObjectParameters(_drawningCruiser.GetPosX,
_drawningCar.GetPosY, _drawningCar.GetWidth, _drawningCar.GetHeight); _drawningCruiser.GetPosY, _drawningCruiser.GetWidth, _drawningCruiser.GetHeight);
} }
} }
public int GetStep => (int)(_drawningCar?.EntityCar?.Step ?? 0); public int GetStep => (int)(_drawningCruiser?.EntityCruiser?.Step ?? 0);
public bool CheckCanMove(DirectionType direction) => public bool CheckCanMove(Direction direction) =>
_drawningCar?.CanMove(direction) ?? false; _drawningCruiser?.CanMove(direction) ?? false;
public void MoveObject(DirectionType direction) => public void MoveObject(Direction direction) =>
_drawningCar?.MoveTransport(direction); _drawningCruiser?.MoveTransport(direction);
} }
} }

View File

@@ -11,32 +11,19 @@ namespace Cruiser.Entities
{ {
public class EntityAdvancedCruiser : EntityCruiser public class EntityAdvancedCruiser : EntityCruiser
{ {
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
public Color AdditionalColor { get; private set; } public Color AdditionalColor { get; private set; }
public bool HelicopterPad { get; private set; }
/// <summary> public bool Coating { get; private set; }
/// Признак (опция) наличия кузова
/// </summary>
public bool BodyKit { get; private set; }
/// <summary>
/// Признак (опция) наличия tent
/// </summary>
public bool Tent { get; private set; }
public EntityAdvancedCruiser(int speed, double weight, Color bodyColor, Color public EntityAdvancedCruiser(int speed, double weight, Color bodyColor, Color
additionalColor, bool bodyKit, bool tent) : base(speed, weight, bodyColor) additionalColor, bool helicopterPad, bool coating) : base(speed, weight, bodyColor)
{ {
AdditionalColor = additionalColor; AdditionalColor = additionalColor;
BodyKit = bodyKit; HelicopterPad = helicopterPad;
Tent = tent; Coating = coating;
}
public void setAdditionalColor(Color color)
{
AdditionalColor = color;
} }
} }
} }

View File

@@ -8,34 +8,19 @@ namespace Cruiser.Entities
{ {
public class EntityCruiser public class EntityCruiser
{ {
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; } public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; } public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; } public Color BodyColor { get; private set; }
/// <summary>
/// Шаг перемещения автомобиля
/// </summary>
public double Step => (double)Speed * 100 / Weight; public double Step => (double)Speed * 100 / Weight;
/// <summary>
/// Конструктор с параметрами
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Основной цвет</param>
public EntityCruiser(int speed, double weight, Color bodyColor) public EntityCruiser(int speed, double weight, Color bodyColor)
{ {
Speed = speed; Speed = speed;
Weight = weight; Weight = weight;
BodyColor = bodyColor; BodyColor = bodyColor;
} }
public void setBodyColor(Color color)
{
BodyColor = color;
}
} }
} }

View File

@@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cruiser.Entities;
namespace Cruiser.DrawningObjects
{
public static class ExtentionDrawingCruiser
{
public static DrawningCruiser? CreateDrawningCruiser(this string info, char separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawningCruiser(Convert.ToInt32(strs[0]), Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
}
if (strs.Length == 7)
{
return new DrawningAdvancedCruiser(Convert.ToInt32(strs[0]), Convert.ToInt32(strs[1]), Color.FromName(strs[2]),
Color.FromName(strs[3]), Convert.ToBoolean(strs[4]), Convert.ToBoolean(strs[5]), width, height);
}
return null;
}
public static string GetDataForSave(this DrawningCruiser drawningcruiser, char separatorForObject)
{
var cruiser = drawningcruiser.EntityCruiser;
if (cruiser == null)
{
return string.Empty;
}
var str = $"{cruiser.Speed}{separatorForObject}{cruiser.Weight}{separatorForObject}{cruiser.BodyColor.Name}";
if (cruiser is not EntityAdvancedCruiser advancedCruiser)
{
return str;
}
return
$"{str}{separatorForObject}{advancedCruiser.AdditionalColor.Name}{separatorForObject}" +
$"{separatorForObject}{advancedCruiser.HelicopterPad}{separatorForObject}{advancedCruiser.Coating}";
}
}
}

View File

@@ -1,195 +0,0 @@
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>
#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.button1 = new System.Windows.Forms.Button();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.buttonDown = new System.Windows.Forms.Button();
this.buttonLeft = new System.Windows.Forms.Button();
this.buttonRight = new System.Windows.Forms.Button();
this.buttonUp = new System.Windows.Forms.Button();
this.buttonCreate = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.ButtonStep = new System.Windows.Forms.Button();
this.SelectedCruiser = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(386, 68);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(112, 34);
this.button1.TabIndex = 0;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
//
// pictureBox1
//
this.pictureBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBox1.Location = new System.Drawing.Point(0, 0);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(667, 358);
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pictureBox1.TabIndex = 0;
this.pictureBox1.TabStop = false;
this.pictureBox1.Click += new System.EventHandler(this.buttonMove_Click);
//
// buttonDown
//
this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDown.BackgroundImage = global::Cruiser.Properties.Resources.вниз;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.buttonDown.Location = new System.Drawing.Point(543, 306);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(30, 30);
this.buttonDown.TabIndex = 1;
this.buttonDown.UseVisualStyleBackColor = true;
this.buttonDown.Click += new System.EventHandler(this.buttonMove_Click);
//
// buttonLeft
//
this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonLeft.BackgroundImage = global::Cruiser.Properties.Resources.влево;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.buttonLeft.Location = new System.Drawing.Point(517, 306);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(30, 30);
this.buttonLeft.TabIndex = 2;
this.buttonLeft.UseVisualStyleBackColor = true;
this.buttonLeft.Click += new System.EventHandler(this.buttonMove_Click);
//
// buttonRight
//
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::Cruiser.Properties.Resources.вправо;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.buttonRight.Location = new System.Drawing.Point(567, 306);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(30, 30);
this.buttonRight.TabIndex = 3;
this.buttonRight.UseVisualStyleBackColor = true;
this.buttonRight.Click += new System.EventHandler(this.buttonMove_Click);
//
// buttonUp
//
this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonUp.BackgroundImage = global::Cruiser.Properties.Resources.вверх;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.buttonUp.Location = new System.Drawing.Point(543, 284);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(30, 30);
this.buttonUp.TabIndex = 4;
this.buttonUp.UseVisualStyleBackColor = true;
this.buttonUp.Click += new System.EventHandler(this.buttonMove_Click);
//
// buttonCreate
//
this.buttonCreate.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonCreate.Location = new System.Drawing.Point(0, 302);
this.buttonCreate.Name = "buttonCreate";
this.buttonCreate.Size = new System.Drawing.Size(218, 34);
this.buttonCreate.TabIndex = 5;
this.buttonCreate.Text = "Создать простую";
this.buttonCreate.UseVisualStyleBackColor = true;
this.buttonCreate.Click += new System.EventHandler(this.buttonCreate_Click);
//
// button2
//
this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.button2.Location = new System.Drawing.Point(210, 301);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(251, 37);
this.button2.TabIndex = 6;
this.button2.Text = "Создать про версию";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// comboBox1
//
this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBox1.FormattingEnabled = true;
this.comboBox1.Items.AddRange(new object[] {
"Центр",
"Угол"});
this.comboBox1.Location = new System.Drawing.Point(415, 22);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(182, 33);
this.comboBox1.TabIndex = 7;
//
// ButtonStep
//
this.ButtonStep.Location = new System.Drawing.Point(485, 70);
this.ButtonStep.Name = "ButtonStep";
this.ButtonStep.Size = new System.Drawing.Size(112, 34);
this.ButtonStep.TabIndex = 8;
this.ButtonStep.Text = "Шаг";
this.ButtonStep.UseVisualStyleBackColor = true;
this.ButtonStep.Click += new System.EventHandler(this.ButtonStep_Click);
//
// SelectedCruiser
//
this.SelectedCruiser.Location = new System.Drawing.Point(210, 261);
this.SelectedCruiser.Name = "SelectedCruiser";
this.SelectedCruiser.Size = new System.Drawing.Size(112, 34);
this.SelectedCruiser.TabIndex = 9;
this.SelectedCruiser.Text = "Выбрать";
this.SelectedCruiser.UseVisualStyleBackColor = true;
this.SelectedCruiser.Click += new System.EventHandler(this.SelectedCruiser_Click);
//
// CruiserForm
//
this.ClientSize = new System.Drawing.Size(667, 358);
this.Controls.Add(this.SelectedCruiser);
this.Controls.Add(this.ButtonStep);
this.Controls.Add(this.comboBox1);
this.Controls.Add(this.button2);
this.Controls.Add(this.buttonCreate);
this.Controls.Add(this.buttonUp);
this.Controls.Add(this.buttonRight);
this.Controls.Add(this.buttonLeft);
this.Controls.Add(this.buttonDown);
this.Controls.Add(this.pictureBox1);
this.Name = "CruiserForm";
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
/// <param name="e"></param>
#endregion
private Button button1;
private PictureBox pictureBox1;
private Button buttonDown;
private Button buttonLeft;
private Button buttonRight;
private Button buttonUp;
private Button buttonCreate;
private Button button2;
private ComboBox comboBox1;
private Button ButtonStep;
private Button SelectedCruiser;
}
}

View File

@@ -1,161 +0,0 @@
using System.Windows.Forms;
using DumpTruck.DrawningObjects;
using DumpTruck.Entities;
using DumpTruck.MovementStrategy;
namespace Cruiser
{
public partial class Form1 : Form
{
private DrawningCar? _drawningCar;
private AbstractStrategy? _abstractStrategy;
private AbstractStrategy? _strategy;
public DrawningCar? SelectedCar { get; private set; }
public Form1()
{
InitializeComponent();
_strategy = null;
SelectedCar = null;
}
private void Draw()
{
if (_drawningCar == null)
{
return;
}
Bitmap bmp = new Bitmap(pictureBox1.Width, pictureBox1.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningCar.DrawTransport(gr);
pictureBox1.Image = bmp;
}
private void buttonMove_Click(object sender, EventArgs e)
{
if (_drawningCar == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
switch (name)
{
case "buttonUp":
_drawningCar.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
_drawningCar.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
_drawningCar.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
_drawningCar.MoveTransport(DirectionType.Right);
break;
}
Draw();
}
private void button2_Click(object sender, EventArgs e)
{
Random random = new();
Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
Color dopColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
if (dialog.ShowDialog() == DialogResult.OK)
{
dopColor = dialog.Color;
}
_drawningCar = new DrawningDumpTruck(random.Next(100, 300),
random.Next(1000, 3000),
color,
dopColor,
Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)),
pictureBox1.Width, pictureBox1.Height);
_drawningCar.SetPosition(random.Next(10, 100), random.Next(10,
100));
Draw();
}
private void ButtonStep_Click(object sender, EventArgs e)
{
if (_drawningCar == null)
{
return;
}
if (comboBox1.Enabled)
{
_abstractStrategy = comboBox1.SelectedIndex
switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(new DrawningObjectCruiser(_drawningCar), pictureBox1.Width,
pictureBox1.Height);
comboBox1.Enabled = false;
}
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBox1.Enabled = true;
_abstractStrategy = null;
}
}
private void buttonCreate_Click(object sender, EventArgs e)
{
Random random = new();
Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
Color dopColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
_drawningCar = new DrawningCar(random.Next(100, 300),
random.Next(1000, 3000),
color,
pictureBox1.Width, pictureBox1.Height);
_drawningCar.SetPosition(random.Next(10, 100), random.Next(10,
100));
Draw();
}
public void SelectedCruiser_Click(object sender, EventArgs e)
{
SelectedCar = _drawningCar;
DialogResult = DialogResult.OK;
}
}
}

View File

@@ -2,15 +2,7 @@
{ {
partial class FormCruiserCollection partial class FormCruiserCollection
{ {
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null; 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) protected override void Dispose(bool disposing)
{ {
if (disposing && (components != null)) if (disposing && (components != null))
@@ -21,94 +13,247 @@
} }
#region Windows Form Designer generated code #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() private void InitializeComponent()
{ {
this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.pictureBoxCruiser = new System.Windows.Forms.PictureBox();
this.panel1 = new System.Windows.Forms.Panel(); this.panelCruiser = new System.Windows.Forms.Panel();
this.ButtonRemoveCar = new System.Windows.Forms.Button(); this.ButtonRefreshCollection = new System.Windows.Forms.Button();
this.ButtonRemoveCruiser = new System.Windows.Forms.Button();
this.textBoxCruiser = new System.Windows.Forms.TextBox();
this.ButtonAddCruiser = new System.Windows.Forms.Button(); this.ButtonAddCruiser = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox(); this.panelSet = new System.Windows.Forms.Panel();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.ButtonDelObject = new System.Windows.Forms.Button();
this.panel1.SuspendLayout(); this.listBoxStorages = new System.Windows.Forms.ListBox();
this.ButtonAddObject = new System.Windows.Forms.Button();
this.textBoxSet = new System.Windows.Forms.TextBox();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.menuStrip = new System.Windows.Forms.MenuStrip();
this.FileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.SaveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.LoadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.buttonSortByType = new System.Windows.Forms.Button();
this.buttonSortByColor = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCruiser)).BeginInit();
this.panelCruiser.SuspendLayout();
this.panelSet.SuspendLayout();
this.menuStrip.SuspendLayout();
this.SuspendLayout(); this.SuspendLayout();
// //
// pictureBox1 // pictureBoxCruiser
// //
this.pictureBox1.Dock = System.Windows.Forms.DockStyle.Fill; this.pictureBoxCruiser.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBox1.Location = new System.Drawing.Point(0, 0); this.pictureBoxCruiser.Location = new System.Drawing.Point(0, 33);
this.pictureBox1.Name = "pictureBox1"; this.pictureBoxCruiser.Name = "pictureBoxCruiser";
this.pictureBox1.Size = new System.Drawing.Size(800, 450); this.pictureBoxCruiser.Size = new System.Drawing.Size(1083, 556);
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; this.pictureBoxCruiser.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pictureBox1.TabIndex = 0; this.pictureBoxCruiser.TabIndex = 0;
this.pictureBox1.TabStop = false; this.pictureBoxCruiser.TabStop = false;
this.pictureBox1.Click += new System.EventHandler(this.pictureBox1_Click);
// //
// panel1 // panelCruiser
// //
this.panel1.Controls.Add(this.ButtonRemoveCar); this.panelCruiser.Controls.Add(this.buttonSortByColor);
this.panel1.Controls.Add(this.ButtonAddCruiser); this.panelCruiser.Controls.Add(this.buttonSortByType);
this.panel1.Controls.Add(this.textBox1); this.panelCruiser.Controls.Add(this.ButtonRefreshCollection);
this.panel1.Location = new System.Drawing.Point(589, 12); this.panelCruiser.Controls.Add(this.ButtonRemoveCruiser);
this.panel1.Name = "panel1"; this.panelCruiser.Controls.Add(this.textBoxCruiser);
this.panel1.Size = new System.Drawing.Size(211, 438); this.panelCruiser.Controls.Add(this.ButtonAddCruiser);
this.panel1.TabIndex = 1; this.panelCruiser.Controls.Add(this.panelSet);
this.panelCruiser.Location = new System.Drawing.Point(786, 36);
this.panelCruiser.Name = "panelCruiser";
this.panelCruiser.Size = new System.Drawing.Size(221, 553);
this.panelCruiser.TabIndex = 1;
// //
// ButtonRemoveCar // ButtonRefreshCollection
// //
this.ButtonRemoveCar.Location = new System.Drawing.Point(31, 168); this.ButtonRefreshCollection.Location = new System.Drawing.Point(45, 500);
this.ButtonRemoveCar.Name = "ButtonRemoveCar"; this.ButtonRefreshCollection.Name = "ButtonRefreshCollection";
this.ButtonRemoveCar.Size = new System.Drawing.Size(150, 34); this.ButtonRefreshCollection.Size = new System.Drawing.Size(138, 41);
this.ButtonRemoveCar.TabIndex = 2; this.ButtonRefreshCollection.TabIndex = 2;
this.ButtonRemoveCar.Text = "Удалить"; this.ButtonRefreshCollection.Text = "Обновить";
this.ButtonRemoveCar.UseVisualStyleBackColor = true; this.ButtonRefreshCollection.UseVisualStyleBackColor = true;
this.ButtonRemoveCar.Click += new System.EventHandler(this.ButtonRemoveCar_Click); this.ButtonRefreshCollection.Click += new System.EventHandler(this.ButtonRefreshCollection_Click);
//
// ButtonRemoveCruiser
//
this.ButtonRemoveCruiser.Location = new System.Drawing.Point(45, 456);
this.ButtonRemoveCruiser.Name = "ButtonRemoveCruiser";
this.ButtonRemoveCruiser.Size = new System.Drawing.Size(138, 38);
this.ButtonRemoveCruiser.TabIndex = 2;
this.ButtonRemoveCruiser.Text = "Удалить";
this.ButtonRemoveCruiser.UseVisualStyleBackColor = true;
this.ButtonRemoveCruiser.Click += new System.EventHandler(this.ButtonRemoveCruiser_Click);
//
// textBoxCruiser
//
this.textBoxCruiser.Location = new System.Drawing.Point(50, 419);
this.textBoxCruiser.Name = "textBoxCruiser";
this.textBoxCruiser.Size = new System.Drawing.Size(133, 31);
this.textBoxCruiser.TabIndex = 3;
// //
// ButtonAddCruiser // ButtonAddCruiser
// //
this.ButtonAddCruiser.Location = new System.Drawing.Point(31, 37); this.ButtonAddCruiser.Location = new System.Drawing.Point(45, 266);
this.ButtonAddCruiser.Name = "ButtonAddCruiser"; this.ButtonAddCruiser.Name = "ButtonAddCruiser";
this.ButtonAddCruiser.Size = new System.Drawing.Size(150, 34); this.ButtonAddCruiser.Size = new System.Drawing.Size(133, 38);
this.ButtonAddCruiser.TabIndex = 3; this.ButtonAddCruiser.TabIndex = 2;
this.ButtonAddCruiser.Text = "Добавить"; this.ButtonAddCruiser.Text = "Добавить";
this.ButtonAddCruiser.UseVisualStyleBackColor = true; this.ButtonAddCruiser.UseVisualStyleBackColor = true;
this.ButtonAddCruiser.Click += new System.EventHandler(this.ButtonAddCruiser_Click); this.ButtonAddCruiser.Click += new System.EventHandler(this.ButtonAddCruiser_Click);
// //
// textBox1 // panelSet
// //
this.textBox1.Location = new System.Drawing.Point(31, 104); this.panelSet.Controls.Add(this.ButtonDelObject);
this.textBox1.Name = "textBox1"; this.panelSet.Controls.Add(this.listBoxStorages);
this.textBox1.Size = new System.Drawing.Size(150, 31); this.panelSet.Controls.Add(this.ButtonAddObject);
this.textBox1.TabIndex = 2; this.panelSet.Controls.Add(this.textBoxSet);
this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged); this.panelSet.Location = new System.Drawing.Point(22, 19);
this.panelSet.Name = "panelSet";
this.panelSet.Size = new System.Drawing.Size(185, 241);
this.panelSet.TabIndex = 0;
//
// ButtonDelObject
//
this.ButtonDelObject.Location = new System.Drawing.Point(18, 175);
this.ButtonDelObject.Name = "ButtonDelObject";
this.ButtonDelObject.Size = new System.Drawing.Size(153, 47);
this.ButtonDelObject.TabIndex = 2;
this.ButtonDelObject.Text = "Удалить набор";
this.ButtonDelObject.UseVisualStyleBackColor = true;
this.ButtonDelObject.Click += new System.EventHandler(this.ButtonDelObject_Click);
//
// listBoxStorages
//
this.listBoxStorages.FormattingEnabled = true;
this.listBoxStorages.ItemHeight = 25;
this.listBoxStorages.Location = new System.Drawing.Point(49, 115);
this.listBoxStorages.Name = "listBoxStorages";
this.listBoxStorages.Size = new System.Drawing.Size(97, 54);
this.listBoxStorages.TabIndex = 3;
this.listBoxStorages.SelectedIndexChanged += new System.EventHandler(this.listBoxObjects_SelectedIndexChanged);
//
// ButtonAddObject
//
this.ButtonAddObject.Location = new System.Drawing.Point(18, 58);
this.ButtonAddObject.Name = "ButtonAddObject";
this.ButtonAddObject.Size = new System.Drawing.Size(153, 51);
this.ButtonAddObject.TabIndex = 2;
this.ButtonAddObject.Text = "Создать набор";
this.ButtonAddObject.UseVisualStyleBackColor = true;
this.ButtonAddObject.Click += new System.EventHandler(this.ButtonAddObject_Click);
//
// textBoxSet
//
this.textBoxSet.Location = new System.Drawing.Point(38, 21);
this.textBoxSet.Name = "textBoxSet";
this.textBoxSet.Size = new System.Drawing.Size(118, 31);
this.textBoxSet.TabIndex = 0;
//
// openFileDialog
//
this.openFileDialog.FileName = "openFileDialog";
this.openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
this.saveFileDialog.Filter = "txt file | *.txt";
//
// menuStrip
//
this.menuStrip.ImageScalingSize = new System.Drawing.Size(24, 24);
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.FileToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(1083, 33);
this.menuStrip.TabIndex = 2;
this.menuStrip.Text = "menuStrip";
//
// FileToolStripMenuItem
//
this.FileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.SaveToolStripMenuItem,
this.LoadToolStripMenuItem});
this.FileToolStripMenuItem.Name = "FileToolStripMenuItem";
this.FileToolStripMenuItem.Size = new System.Drawing.Size(69, 29);
this.FileToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(200, 34);
this.SaveToolStripMenuItem.Text = "Сохранить";
this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// LoadToolStripMenuItem
//
this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(200, 34);
this.LoadToolStripMenuItem.Text = "Загрузить";
this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
// buttonSortByType
//
this.buttonSortByType.Location = new System.Drawing.Point(50, 320);
this.buttonSortByType.Name = "buttonSortByType";
this.buttonSortByType.Size = new System.Drawing.Size(128, 33);
this.buttonSortByType.TabIndex = 4;
this.buttonSortByType.Text = "Сортировка по типу";
this.buttonSortByType.UseVisualStyleBackColor = true;
this.buttonSortByType.Click += new System.EventHandler(this.ButtonSortByType_Click);
//
// buttonSortByColor
//
this.buttonSortByColor.Location = new System.Drawing.Point(50, 372);
this.buttonSortByColor.Name = "buttonSortByColor";
this.buttonSortByColor.Size = new System.Drawing.Size(133, 27);
this.buttonSortByColor.TabIndex = 5;
this.buttonSortByColor.Text = "Сортировка по цвету";
this.buttonSortByColor.UseVisualStyleBackColor = true;
this.buttonSortByColor.Click += new System.EventHandler(this.ButtonSortByColor_Click);
// //
// FormCruiserCollection // FormCruiserCollection
// //
this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F); this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450); this.ClientSize = new System.Drawing.Size(1083, 589);
this.Controls.Add(this.panel1); this.Controls.Add(this.panelCruiser);
this.Controls.Add(this.pictureBox1); this.Controls.Add(this.pictureBoxCruiser);
this.Controls.Add(this.menuStrip);
this.MainMenuStrip = this.menuStrip;
this.Name = "FormCruiserCollection"; this.Name = "FormCruiserCollection";
this.Text = "FormCruiserCollection"; this.Text = "FormCruiserCollection";
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxCruiser)).EndInit();
this.panel1.ResumeLayout(false); this.panelCruiser.ResumeLayout(false);
this.panel1.PerformLayout(); this.panelCruiser.PerformLayout();
this.panelSet.ResumeLayout(false);
this.panelSet.PerformLayout();
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.ResumeLayout(false); this.ResumeLayout(false);
this.PerformLayout(); this.PerformLayout();
} }
#endregion #endregion
private PictureBox pictureBox1; private PictureBox pictureBoxCruiser;
private Panel panel1; private Panel panelCruiser;
private Button ButtonRemoveCar; private Panel panelSet;
private TextBox textBoxSet;
private ListBox listBoxStorages;
private Button ButtonAddObject;
private Button ButtonDelObject;
private Button ButtonAddCruiser; private Button ButtonAddCruiser;
private TextBox textBox1; private Button ButtonRemoveCruiser;
private TextBox textBoxCruiser;
private Button ButtonRefreshCollection;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private MenuStrip menuStrip;
private ToolStripMenuItem FileToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private Button buttonSortByColor;
private Button buttonSortByType;
} }
} }

View File

@@ -1,5 +1,5 @@
 using Cruiser.Generics;
using DumpTruck.Generics; using Cruiser.DrawningObjects;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
@@ -9,91 +9,218 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using Cruiser; using Cruiser.Exceptions;
using DumpTruck.DrawningObjects; using System.Xml.Linq;
using DumpTruck.Generics; using Serilog;
using DumpTruck.MovementStrategy; using System.Numerics;
namespace Cruiser namespace Cruiser
{ {
public partial class FormCruiserCollection : Form public partial class FormCruiserCollection : Form
{ {
private readonly CruiserGenericCollection<DrawningCar, DrawningObjectCruiser> _cars; private readonly CruiserGenericStorage _storage;
public FormCruiserCollection() public FormCruiserCollection()
{ {
InitializeComponent(); InitializeComponent();
_cars = new CruiserGenericCollection<DrawningCar, DrawningObjectCruiser>(pictureBox1.Width, pictureBox1.Height); _storage = new CruiserGenericStorage(pictureBoxCruiser.Width, pictureBoxCruiser.Height);
} }
private void ReloadObjects()
private void pictureBox1_Click(object sender, EventArgs e)
{ {
int index = listBoxStorages.SelectedIndex;
listBoxStorages.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++)
{
listBoxStorages.Items.Add(_storage.Keys[i].Name);
}
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;
}
}
private void ButtonAddObject_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxSet.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_storage.AddSet(textBoxSet.Text);
ReloadObjects();
Log.Information($"Добавлен набор: {textBoxSet.Text}");
}
private void listBoxObjects_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBoxCruiser.Image = _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowCruisers();
}
private void ButtonDelObject_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
if (MessageBox.Show($"Удалить объект{listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes)
{
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
_storage.DelSet(name);
ReloadObjects();
Log.Information($"Удален набор: {name}");
}
} }
private void ButtonAddCruiser_Click(object sender, EventArgs e) private void ButtonAddCruiser_Click(object sender, EventArgs e)
{ {
Form1 form = new(); if (listBoxStorages.SelectedIndex == -1)
if (form.ShowDialog() == DialogResult.OK)
{ {
if (_cars + form.SelectedCar != null) return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
FormCruiserConfig form = new();
form.Show();
Action<DrawningCruiser>? cruiserDelegate = new((m) =>
{
try
{ {
bool q = obj + m;
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBox1.Image = _cars.ShowCars(); pictureBoxCruiser.Image = obj.ShowCruisers();
Log.Information($"Добавлен объект в коллекцию {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
} }
else catch (StorageOverflowException ex)
{ {
MessageBox.Show("Не удалось добавить объект"); Log.Warning($"Коллекция {listBoxStorages.SelectedItem.ToString() ?? string.Empty} переполнена");
MessageBox.Show(ex.Message);
} }
} catch (ArgumentException)
{
Log.Warning($"Добавляемый объект уже существует в коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
MessageBox.Show("Добавляемый объект уже сущесвует в коллекции");
}
});
form.AddEvent(cruiserDelegate);
} }
private void ButtonRemoveCruiser_Click(object sender, EventArgs e)
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("Удалить объект?", "Удаление", if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{ {
return; return;
} }
int pos; try
if (textBox1.Text == null || !int.TryParse(textBox1.Text, out pos))
{
MessageBox.Show("Введите номер парковочного места");
return;
}
if (_cars - pos != null)
{ {
int pos = Convert.ToInt32(textBoxCruiser.Text);
var q = obj - pos;
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
pictureBox1.Image = _cars.ShowCars(); Log.Information($"Удален объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty} по номеру {pos}");
pictureBoxCruiser.Image = obj.ShowCruisers();
} }
else catch (CruiserNotFoundException ex)
{ {
MessageBox.Show("Не удалось удалить объект"); Log.Warning($"Не получилось удалить объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
MessageBox.Show(ex.Message);
}
catch (FormatException)
{
Log.Warning($"Было введено не число");
MessageBox.Show("Введите число");
} }
} }
private void ButtonRefreshCollection_Click(object sender, EventArgs e) private void ButtonRefreshCollection_Click(object sender, EventArgs e)
{ {
pictureBox1.Image = _cars.ShowCars(); if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
pictureBoxCruiser.Image = obj.ShowCruisers();
}
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
Log.Information($"Файл {saveFileDialog.FileName} успешно сохранен");
}
catch (Exception ex)
{
Log.Warning("Не удалось сохранить");
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
} }
private void maskedTextBoxNumber_MaskInputRejected(object sender, MaskInputRejectedEventArgs e) private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
Log.Information($"Файл {openFileDialog.FileName} успешно загружен");
foreach (var collection in _storage.Keys)
{
listBoxStorages.Items.Add(collection);
}
ReloadObjects();
}
catch (Exception ex)
{
Log.Warning("Не удалось загрузить");
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
} }
private void ButtonSortByType_Click(object sender, EventArgs e) => CompareCruiser(new CruiserCompareByType());
private void textBox1_TextChanged(object sender, EventArgs e) private void ButtonSortByColor_Click(object sender, EventArgs e) => CompareCruiser(new CruiserCompareByColor());
private void CompareCruiser(IComparer<DrawningCruiser?> comparer)
{ {
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
obj.Sort(comparer);
pictureBoxCruiser.Image = obj.ShowCruisers();
} }
} }
} }

View File

@@ -57,4 +57,13 @@
<resheader name="writer"> <resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </resheader>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>201, 17</value>
</metadata>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>379, 17</value>
</metadata>
</root> </root>

View File

@@ -0,0 +1,381 @@
namespace Cruiser
{
partial class FormCruiserConfig
{
/// <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.groupBoxCruiser = new System.Windows.Forms.GroupBox();
this.checkBoxMissileSilos = new System.Windows.Forms.CheckBox();
this.buttonCancel = new System.Windows.Forms.Button();
this.buttonAdd = new System.Windows.Forms.Button();
this.panelOrchid = new System.Windows.Forms.Panel();
this.label_addit_color = new System.Windows.Forms.Label();
this.label_color = new System.Windows.Forms.Label();
this.pictureBoxCruiser = new System.Windows.Forms.PictureBox();
this.labelAdvanced = new System.Windows.Forms.Label();
this.labelBasic = new System.Windows.Forms.Label();
this.groupBoxColor = new System.Windows.Forms.GroupBox();
this.panelColor = new System.Windows.Forms.Panel();
this.panelPink = new System.Windows.Forms.Panel();
this.panelViolet = new System.Windows.Forms.Panel();
this.panelBlue = new System.Windows.Forms.Panel();
this.panelLightBlue = new System.Windows.Forms.Panel();
this.panelPurple = new System.Windows.Forms.Panel();
this.panelBlack = new System.Windows.Forms.Panel();
this.panelWhite = new System.Windows.Forms.Panel();
this.checkBoxHelicopterPad = new System.Windows.Forms.CheckBox();
this.numericUpDownWeight = new System.Windows.Forms.NumericUpDown();
this.numericUpDownSpeed = new System.Windows.Forms.NumericUpDown();
this.labelWeight = new System.Windows.Forms.Label();
this.labelSpeed = new System.Windows.Forms.Label();
this.groupBoxCruiser.SuspendLayout();
this.panelOrchid.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCruiser)).BeginInit();
this.groupBoxColor.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).BeginInit();
this.SuspendLayout();
//
// groupBoxCruiser
//
this.groupBoxCruiser.Controls.Add(this.checkBoxMissileSilos);
this.groupBoxCruiser.Controls.Add(this.buttonCancel);
this.groupBoxCruiser.Controls.Add(this.buttonAdd);
this.groupBoxCruiser.Controls.Add(this.panelOrchid);
this.groupBoxCruiser.Controls.Add(this.labelAdvanced);
this.groupBoxCruiser.Controls.Add(this.labelBasic);
this.groupBoxCruiser.Controls.Add(this.groupBoxColor);
this.groupBoxCruiser.Controls.Add(this.checkBoxHelicopterPad);
this.groupBoxCruiser.Controls.Add(this.numericUpDownWeight);
this.groupBoxCruiser.Controls.Add(this.numericUpDownSpeed);
this.groupBoxCruiser.Controls.Add(this.labelWeight);
this.groupBoxCruiser.Controls.Add(this.labelSpeed);
this.groupBoxCruiser.Location = new System.Drawing.Point(57, 43);
this.groupBoxCruiser.Name = "groupBoxCruiser";
this.groupBoxCruiser.Size = new System.Drawing.Size(1163, 391);
this.groupBoxCruiser.TabIndex = 0;
this.groupBoxCruiser.TabStop = false;
this.groupBoxCruiser.Text = "Параметры";
//
// checkBoxMissileSilos
//
this.checkBoxMissileSilos.AutoSize = true;
this.checkBoxMissileSilos.Location = new System.Drawing.Point(33, 277);
this.checkBoxMissileSilos.Name = "checkBoxMissileSilos";
this.checkBoxMissileSilos.Size = new System.Drawing.Size(232, 29);
this.checkBoxMissileSilos.TabIndex = 12;
this.checkBoxMissileSilos.Text = "Наличие ракетных шахт";
this.checkBoxMissileSilos.UseVisualStyleBackColor = true;
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(991, 321);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(127, 38);
this.buttonCancel.TabIndex = 11;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
//
// buttonAdd
//
this.buttonAdd.Location = new System.Drawing.Point(838, 321);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(136, 38);
this.buttonAdd.TabIndex = 10;
this.buttonAdd.Text = "Добавить";
this.buttonAdd.UseVisualStyleBackColor = true;
this.buttonAdd.Click += new System.EventHandler(this.ButtonAdd_Click);
//
// panelOrchid
//
this.panelOrchid.AllowDrop = true;
this.panelOrchid.Controls.Add(this.label_addit_color);
this.panelOrchid.Controls.Add(this.label_color);
this.panelOrchid.Controls.Add(this.pictureBoxCruiser);
this.panelOrchid.Location = new System.Drawing.Point(822, 45);
this.panelOrchid.Name = "panelOrchid";
this.panelOrchid.Size = new System.Drawing.Size(312, 261);
this.panelOrchid.TabIndex = 9;
this.panelOrchid.DragDrop += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragDrop);
this.panelOrchid.DragEnter += new System.Windows.Forms.DragEventHandler(this.PanelObject_DragEnter);
//
// label_addit_color
//
this.label_addit_color.AllowDrop = true;
this.label_addit_color.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.label_addit_color.Location = new System.Drawing.Point(169, 23);
this.label_addit_color.Name = "label_addit_color";
this.label_addit_color.Size = new System.Drawing.Size(117, 38);
this.label_addit_color.TabIndex = 10;
this.label_addit_color.Text = "Доп.цвет";
this.label_addit_color.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.label_addit_color.DragDrop += new System.Windows.Forms.DragEventHandler(this.labelColor_DragDrop);
this.label_addit_color.DragEnter += new System.Windows.Forms.DragEventHandler(this.labelColor_DragEnter);
//
// label_color
//
this.label_color.AllowDrop = true;
this.label_color.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.label_color.Location = new System.Drawing.Point(30, 23);
this.label_color.Name = "label_color";
this.label_color.Size = new System.Drawing.Size(110, 38);
this.label_color.TabIndex = 9;
this.label_color.Text = "Цвет";
this.label_color.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.label_color.DragDrop += new System.Windows.Forms.DragEventHandler(this.labelColor_DragDrop);
this.label_color.DragEnter += new System.Windows.Forms.DragEventHandler(this.labelColor_DragEnter);
//
// pictureBoxCruiser
//
this.pictureBoxCruiser.Location = new System.Drawing.Point(76, 64);
this.pictureBoxCruiser.Name = "pictureBoxCruiser";
this.pictureBoxCruiser.Size = new System.Drawing.Size(163, 178);
this.pictureBoxCruiser.TabIndex = 8;
this.pictureBoxCruiser.TabStop = false;
//
// labelAdvanced
//
this.labelAdvanced.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelAdvanced.Location = new System.Drawing.Point(521, 293);
this.labelAdvanced.Name = "labelAdvanced";
this.labelAdvanced.Size = new System.Drawing.Size(141, 47);
this.labelAdvanced.TabIndex = 7;
this.labelAdvanced.Text = "Продвинутый";
this.labelAdvanced.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelAdvanced.MouseDown += new System.Windows.Forms.MouseEventHandler(this.LabelObject_MouseDown);
//
// labelBasic
//
this.labelBasic.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.labelBasic.Location = new System.Drawing.Point(369, 293);
this.labelBasic.Name = "labelBasic";
this.labelBasic.Size = new System.Drawing.Size(131, 47);
this.labelBasic.TabIndex = 6;
this.labelBasic.Text = "Простой";
this.labelBasic.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.labelBasic.MouseDown += new System.Windows.Forms.MouseEventHandler(this.LabelObject_MouseDown);
//
// groupBoxColor
//
this.groupBoxColor.Controls.Add(this.panelColor);
this.groupBoxColor.Controls.Add(this.panelPink);
this.groupBoxColor.Controls.Add(this.panelViolet);
this.groupBoxColor.Controls.Add(this.panelBlue);
this.groupBoxColor.Controls.Add(this.panelLightBlue);
this.groupBoxColor.Controls.Add(this.panelPurple);
this.groupBoxColor.Controls.Add(this.panelBlack);
this.groupBoxColor.Controls.Add(this.panelWhite);
this.groupBoxColor.Location = new System.Drawing.Point(335, 40);
this.groupBoxColor.Name = "groupBoxColor";
this.groupBoxColor.Size = new System.Drawing.Size(357, 231);
this.groupBoxColor.TabIndex = 5;
this.groupBoxColor.TabStop = false;
this.groupBoxColor.Text = "Цвета";
//
// panelColor
//
this.panelColor.BackColor = System.Drawing.Color.Fuchsia;
this.panelColor.Location = new System.Drawing.Point(264, 153);
this.panelColor.Name = "panelColor";
this.panelColor.Size = new System.Drawing.Size(53, 49);
this.panelColor.TabIndex = 7;
//
// panelPink
//
this.panelPink.BackColor = System.Drawing.Color.Violet;
this.panelPink.Location = new System.Drawing.Point(180, 153);
this.panelPink.Name = "panelPink";
this.panelPink.Size = new System.Drawing.Size(53, 49);
this.panelPink.TabIndex = 6;
//
// panelViolet
//
this.panelViolet.BackColor = System.Drawing.Color.DarkTurquoise;
this.panelViolet.Location = new System.Drawing.Point(108, 153);
this.panelViolet.Name = "panelViolet";
this.panelViolet.Size = new System.Drawing.Size(53, 49);
this.panelViolet.TabIndex = 5;
//
// panelBlue
//
this.panelBlue.BackColor = System.Drawing.Color.PaleTurquoise;
this.panelBlue.Location = new System.Drawing.Point(34, 153);
this.panelBlue.Name = "panelBlue";
this.panelBlue.Size = new System.Drawing.Size(53, 49);
this.panelBlue.TabIndex = 4;
//
// panelLightBlue
//
this.panelLightBlue.BackColor = System.Drawing.Color.Purple;
this.panelLightBlue.Location = new System.Drawing.Point(264, 44);
this.panelLightBlue.Name = "panelLightBlue";
this.panelLightBlue.Size = new System.Drawing.Size(53, 49);
this.panelLightBlue.TabIndex = 3;
//
// panelPurple
//
this.panelPurple.BackColor = System.Drawing.Color.DarkOrchid;
this.panelPurple.Location = new System.Drawing.Point(186, 44);
this.panelPurple.Name = "panelPurple";
this.panelPurple.Size = new System.Drawing.Size(53, 49);
this.panelPurple.TabIndex = 2;
//
// panelBlack
//
this.panelBlack.BackColor = System.Drawing.SystemColors.ActiveCaptionText;
this.panelBlack.Location = new System.Drawing.Point(108, 44);
this.panelBlack.Name = "panelBlack";
this.panelBlack.Size = new System.Drawing.Size(53, 49);
this.panelBlack.TabIndex = 1;
//
// panelWhite
//
this.panelWhite.BackColor = System.Drawing.SystemColors.ButtonHighlight;
this.panelWhite.Location = new System.Drawing.Point(32, 44);
this.panelWhite.Name = "panelWhite";
this.panelWhite.Size = new System.Drawing.Size(55, 49);
this.panelWhite.TabIndex = 0;
//
// checkBoxHelicopterPad
//
this.checkBoxHelicopterPad.AutoSize = true;
this.checkBoxHelicopterPad.Location = new System.Drawing.Point(33, 213);
this.checkBoxHelicopterPad.Name = "checkBoxHelicopterPad";
this.checkBoxHelicopterPad.Size = new System.Drawing.Size(310, 29);
this.checkBoxHelicopterPad.TabIndex = 4;
this.checkBoxHelicopterPad.Text = "Наличие площадки под вертолет";
this.checkBoxHelicopterPad.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
this.numericUpDownWeight.Location = new System.Drawing.Point(128, 143);
this.numericUpDownWeight.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.numericUpDownWeight.Minimum = new decimal(new int[] {
100,
0,
0,
0});
this.numericUpDownWeight.Name = "numericUpDownWeight";
this.numericUpDownWeight.Size = new System.Drawing.Size(84, 31);
this.numericUpDownWeight.TabIndex = 3;
this.numericUpDownWeight.Value = new decimal(new int[] {
100,
0,
0,
0});
//
// numericUpDownSpeed
//
this.numericUpDownSpeed.Location = new System.Drawing.Point(128, 75);
this.numericUpDownSpeed.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.numericUpDownSpeed.Minimum = new decimal(new int[] {
100,
0,
0,
0});
this.numericUpDownSpeed.Name = "numericUpDownSpeed";
this.numericUpDownSpeed.Size = new System.Drawing.Size(74, 31);
this.numericUpDownSpeed.TabIndex = 2;
this.numericUpDownSpeed.Value = new decimal(new int[] {
100,
0,
0,
0});
//
// labelWeight
//
this.labelWeight.AutoSize = true;
this.labelWeight.Location = new System.Drawing.Point(33, 145);
this.labelWeight.Name = "labelWeight";
this.labelWeight.Size = new System.Drawing.Size(43, 25);
this.labelWeight.TabIndex = 1;
this.labelWeight.Text = "Вес:";
//
// labelSpeed
//
this.labelSpeed.AutoSize = true;
this.labelSpeed.Location = new System.Drawing.Point(33, 75);
this.labelSpeed.Name = "labelSpeed";
this.labelSpeed.Size = new System.Drawing.Size(93, 25);
this.labelSpeed.TabIndex = 0;
this.labelSpeed.Text = "Скорость:";
//
// FormCruiserConfig
//
this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1279, 552);
this.Controls.Add(this.groupBoxCruiser);
this.Name = "FormCruiserConfig";
this.Text = "Создание объекта";
this.groupBoxCruiser.ResumeLayout(false);
this.groupBoxCruiser.PerformLayout();
this.panelOrchid.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCruiser)).EndInit();
this.groupBoxColor.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWeight)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownSpeed)).EndInit();
this.ResumeLayout(false);
}
#endregion
private GroupBox groupBoxCruiser;
private Button buttonCancel;
private Button buttonAdd;
private Panel panelOrchid;
private Label label_addit_color;
private Label label_color;
private PictureBox pictureBoxCruiser;
private Label labelAdvanced;
private Label labelBasic;
private GroupBox groupBoxColor;
private Panel panelBlack;
private Panel panelWhite;
private CheckBox checkBoxHelicopterPad;
private NumericUpDown numericUpDownWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelWeight;
private Label labelSpeed;
private CheckBox checkBoxMissileSilos;
private Panel panelColor;
private Panel panelPink;
private Panel panelViolet;
private Panel panelBlue;
private Panel panelLightBlue;
private Panel panelPurple;
}
}

View File

@@ -0,0 +1,126 @@
using Cruiser.DrawningObjects;
using Cruiser.Entities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Button;
namespace Cruiser
{
public partial class FormCruiserConfig : Form
{
DrawningCruiser? _cruiser = null;
public event Action<DrawningCruiser>? EventAddCruiser;
public FormCruiserConfig()
{
InitializeComponent();
panelWhite.MouseDown += PanelColor_MouseDown;
panelBlack.MouseDown += PanelColor_MouseDown;
panelLightBlue.MouseDown += PanelColor_MouseDown;
panelBlue.MouseDown += PanelColor_MouseDown;
panelPink.MouseDown += PanelColor_MouseDown;
panelViolet.MouseDown += PanelColor_MouseDown;
panelPurple.MouseDown += PanelColor_MouseDown;
panelOrchid.MouseDown += PanelColor_MouseDown;
buttonCancel.Click += (s, e) => Close();
}
private void DrawCruiser()
{
Bitmap bmp = new(pictureBoxCruiser.Width, pictureBoxCruiser.Height);
Graphics gr = Graphics.FromImage(bmp);
_cruiser?.SetPosition(5, 5);
_cruiser?.DrawTransport(gr);
pictureBoxCruiser.Image = bmp;
}
public void AddEvent(Action<DrawningCruiser> ev)
{
if (EventAddCruiser == null)
{
EventAddCruiser = ev;
}
else
{
EventAddCruiser += ev;
}
}
private void LabelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label)?.DoDragDrop((sender as Label)?.Name,
DragDropEffects.Move | DragDropEffects.Copy);
}
private void PanelObject_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(DataFormats.Text) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void PanelObject_DragDrop(object sender, DragEventArgs e)
{
switch (e.Data?.GetData(DataFormats.Text).ToString())
{
case "labelBasic":
_cruiser = new DrawningCruiser((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value,
Color.White, pictureBoxCruiser.Width, pictureBoxCruiser.Height);
break;
case "labelAdvanced":
_cruiser = new DrawningAdvancedCruiser((int)numericUpDownSpeed.Value, (int)numericUpDownWeight.Value,
Color.White, Color.Black, checkBoxHelicopterPad.Checked, checkBoxMissileSilos.Checked,
pictureBoxCruiser.Width, pictureBoxCruiser.Height);
break;
}
label_color.BackColor = Color.Empty;
label_addit_color.BackColor = Color.Empty;
DrawCruiser();
}
private void PanelColor_MouseDown(object? sender, MouseEventArgs e)
{
(sender as Control)?.DoDragDrop((sender as Control)?.BackColor, DragDropEffects.Move | DragDropEffects.Copy);
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
EventAddCruiser?.Invoke(_cruiser);
Close();
}
private void labelColor_DragDrop(object sender, DragEventArgs e)
{
if (_cruiser?.EntityCruiser == null)
return;
switch (((Label)sender).Name)
{
case "label_color":
_cruiser?.EntityCruiser?.setBodyColor((Color)e.Data.GetData(typeof(Color)));
break;
case "label_addit_color":
if (!(_cruiser is DrawningAdvancedCruiser))
return;
(_cruiser.EntityCruiser as EntityAdvancedCruiser)?.setAdditionalColor(color: (Color)e.Data.GetData(typeof(Color)));
break;
}
DrawCruiser();
}
private void labelColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
}
}

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

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

View File

@@ -1,5 +1,4 @@
using DumpTruck.MovementStrategy; using System;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@@ -21,7 +20,6 @@ namespace Cruiser.MovementStrategy
objParams.DownBorder <= FieldHeight && objParams.DownBorder <= FieldHeight &&
objParams.DownBorder + GetStep() >= FieldHeight; objParams.DownBorder + GetStep() >= FieldHeight;
} }
protected override void MoveToTarget() protected override void MoveToTarget()
{ {
var objParams = GetObjectParameters; var objParams = GetObjectParameters;
@@ -29,22 +27,31 @@ namespace Cruiser.MovementStrategy
{ {
return; return;
} }
var diffX = FieldWidth - objParams.ObjectMiddleHorizontal; var diffX = objParams.RightBorder - FieldWidth;
if (Math.Abs(diffX) > GetStep()) if (Math.Abs(diffX) > GetStep())
{ {
if (diffX > 0)
MoveRight(); {
MoveLeft();
}
else
{
MoveRight();
}
} }
var diffY = FieldHeight - objParams.ObjectMiddleVertical; var diffY = objParams.DownBorder - FieldHeight;
if (Math.Abs(diffY) > GetStep()) if (Math.Abs(diffY) > GetStep())
{ {
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
MoveDown(); }
} }
} }
} }
} }

View File

@@ -1,5 +1,4 @@
using DumpTruck.MovementStrategy; using System;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;

View File

@@ -6,46 +6,18 @@ using System.Threading.Tasks;
namespace Cruiser.MovementStrategy namespace Cruiser.MovementStrategy
{ {
/// <summary>
/// Параметры-координаты объекта
/// </summary>
public class ObjectParameters public class ObjectParameters
{ {
private readonly int _x; private readonly int _x;
private readonly int _y; private readonly int _y;
private readonly int _width; private readonly int _width;
private readonly int _height; private readonly int _height;
/// <summary>
/// Левая граница
/// </summary>
public int LeftBorder => _x; public int LeftBorder => _x;
/// <summary>
/// Верхняя граница
/// </summary>
public int TopBorder => _y; public int TopBorder => _y;
/// <summary>
/// Правая граница
/// </summary>
public int RightBorder => _x + _width; public int RightBorder => _x + _width;
/// <summary>
/// Нижняя граница
/// </summary>
public int DownBorder => _y + _height; public int DownBorder => _y + _height;
/// <summary>
/// Середина объекта
/// </summary>
public int ObjectMiddleHorizontal => _x + _width / 2; public int ObjectMiddleHorizontal => _x + _width / 2;
/// <summary>
/// Середина объекта
/// </summary>
public int ObjectMiddleVertical => _y + _height / 2; 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) public ObjectParameters(int x, int y, int width, int height)
{ {
_x = x; _x = x;

View File

@@ -1,16 +1,40 @@
using Serilog;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;
using Serilog.Formatting.Json;
using Serilog.Configuration;
using Microsoft.Extensions.Configuration;
namespace Cruiser namespace Cruiser
{ {
internal static class Program internal static class Program
{ {
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread] [STAThread]
static void Main() static void Main()
{ {
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: $"{pathNeed}appsettings.json", optional: false, reloadOnChange: true)
.Build();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormCruiserCollection()); Application.Run(new FormCruiserCollection());
} }
} }

View File

@@ -1,102 +1,78 @@
using System; using Cruiser.Exceptions;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Cruiser.Exceptions;
using System.Numerics;
namespace Cruiser.Generics namespace Cruiser.Generics
{ {
internal class SetGeneric<T> internal class SetGeneric<T>
where T : class where T : class
{ {
/// <summary> private readonly List<T?> _places;
/// Массив объектов, которые храним private readonly int _maxCount;
/// </summary> public int Count => _places.Count;
private readonly T?[] _places;
/// <summary>
/// Количество объектов в массиве
/// </summary>
public int Count => _places.Length;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
///
public int startPointer = 0;
public SetGeneric(int count) public SetGeneric(int count)
{ {
_places = new T?[count]; _maxCount = count;
_places = new List<T?>(count);
} }
/// <summary>
/// Добавление объекта в набор public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
/// </summary>
/// <param name="car">Добавляемый автомобиль</param> public void Insert(T cruiser, IEqualityComparer<T>? equal = null)
/// <returns></returns>
public int Insert(T cruiser)
{ {
if (_places[Count - 1] != null) if (_places.Count == _maxCount)
return -1; throw new StorageOverflowException(_maxCount);
return Insert(cruiser, 0); Insert(cruiser, 0, equal);
} }
/// <summary> public void Insert(T cruiser, int position, IEqualityComparer<T>? equal = null)
/// Добавление объекта в набор на конкретную позицию {
/// </summary> if (_places.Count == _maxCount)
/// <param name="car">Добавляемый автомобиль</param> throw new StorageOverflowException(_maxCount);
/// <param name="position">Позиция</param> if (!(position >= 0 && position <= Count))
/// <returns></returns> throw new Exception("Неверная позиция для вставки");
public int Insert(T cruiser, int position) if (equal != null)
{
if (_places.Contains(cruiser, equal))
throw new ArgumentException(nameof(cruiser));
}
_places.Insert(position, cruiser);
}
public void Remove(int position)
{ {
if (!(position >= 0 && position < Count)) if (!(position >= 0 && position < Count))
return -1; throw new CruiserNotFoundException(position);
if (_places[position] != null) _places.RemoveAt(position);
{
int indexEnd = position + 1;
while (_places[indexEnd] != null)
{
indexEnd++;
}
for (int i = indexEnd + 1; i > position; i--)
{
_places[i] = _places[i - 1];
}
}
_places[position] = cruiser;
return position;
} }
// TODO проверка, что элемент массива по этой позиции пустой, если нет, то public T? this[int position]
// проверка, что после вставляемого элемента в массиве есть пустой элемент
// сдвиг всех объектов, находящихся справа от позиции до первого пустого элемента
// TODO вставка по позиции
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public bool Remove(int position)
{ {
if (position < Count && position >= 0) get
{ {
_places[position] = null; if (!(position >= 0 && position < Count))
return true; return null;
return _places[position];
}
set
{
if (!(position >= 0 && position < Count && _places.Count < _maxCount))
return;
_places.Insert(position, value);
} }
return false;
} }
/// <summary> public IEnumerable<T?> GetCruiser(int? maxCruisers = null)
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T? Get(int position)
{ {
if (position < Count && position >= 0) { return _places[position]; } for (int i = 0; i < _places.Count; ++i)
return null; {
yield return _places[i];
if (maxCruisers.HasValue && i == maxCruisers.Value)
{
yield break;
}
}
} }
} }
} }

View File

@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Cruiser.Exceptions
{
[Serializable]
internal class StorageOverflowException : ApplicationException
{
public StorageOverflowException(int count) : base($"В наборе превышено допустимое количество: {count}") { }
public StorageOverflowException() : base() { }
public StorageOverflowException(string message) : base(message) { }
public StorageOverflowException(string message, Exception exception) : base(message, exception) { }
protected StorageOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

@@ -0,0 +1,15 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": { "path": "log.log" }
}
],
"Properties": {
"Application": "Sample"
}
}
}