Compare commits

...

17 Commits
main ... lab_8

Author SHA1 Message Date
K
e544555b7b lab8 2023-12-18 18:54:06 +03:00
K
6758441ee8 IevlewaMD_lab8 2023-12-17 00:53:51 +03:00
K
e2ac931dfd lab_8 2023-12-12 17:42:31 +03:00
chtzsch ~
9089b795a5 lab7 2023-11-29 14:48:34 +03:00
chtzsch ~
225058cf52 lab7 2023-11-29 14:42:00 +03:00
chtzsch ~
38c74b051e lab7 2023-11-29 13:09:40 +03:00
chtzsch ~
1f7f3bdc1d lab_6 2023-11-28 22:39:23 +03:00
chtzsch ~
51f2664d20 lab_6(storage) 2023-11-28 22:34:30 +03:00
chtzsch ~
e9d5335db9 lab_6 2023-11-28 20:44:01 +03:00
chtzsch ~
bac06ec21f lab5 2023-11-15 13:45:37 +03:00
chtzsch ~
7a57f00e6e lab_4 2023-11-01 12:22:40 +03:00
chtzsch ~
4dd8e12530 lab_4 2023-11-01 12:18:13 +03:00
chtzsch ~
0b6de2c28b lab3 2023-10-31 18:25:09 +03:00
chtzsch ~
02d57aca01 lab_3 2023-10-18 14:36:10 +03:00
chtzsch ~
72e2df80a7 lab_02 2023-09-20 13:54:36 +03:00
chtzsch ~
c6a5960e15 Lab01_base 2023-09-19 19:24:05 +03:00
chtzsch ~
86a6f5b9da lab01_BASE 2023-09-19 19:08:00 +03:00
45 changed files with 3810 additions and 125 deletions

View File

@ -1,41 +0,0 @@

namespace SpeedBoat
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Text = "Form1";
}
#endregion
}
}

View File

@ -1,21 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SpeedBoat
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}

View File

@ -1,23 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SpeedBoat
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}

View File

@ -1,9 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net5.0-windows</TargetFramework>
<UseWindowsForms>true</UseWindowsForms>
</PropertyGroup>
</Project>

View File

@ -3,7 +3,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.31729.503
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SpeedBoat", "SpeedBoat\SpeedBoat.csproj", "{CA504B35-DFE8-449C-97F5-02C7D392541A}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "speed_Boat", "speed_Boat\speed_Boat.csproj", "{69814DF7-C284-4ACE-A27E-C43EAA333896}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -11,15 +11,15 @@ Global
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{CA504B35-DFE8-449C-97F5-02C7D392541A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CA504B35-DFE8-449C-97F5-02C7D392541A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CA504B35-DFE8-449C-97F5-02C7D392541A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CA504B35-DFE8-449C-97F5-02C7D392541A}.Release|Any CPU.Build.0 = Release|Any CPU
{69814DF7-C284-4ACE-A27E-C43EAA333896}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{69814DF7-C284-4ACE-A27E-C43EAA333896}.Debug|Any CPU.Build.0 = Debug|Any CPU
{69814DF7-C284-4ACE-A27E-C43EAA333896}.Release|Any CPU.ActiveCfg = Release|Any CPU
{69814DF7-C284-4ACE-A27E-C43EAA333896}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {74698B56-6881-4BCE-9439-4D163E6F4EC5}
SolutionGuid = {BAB091BF-94E7-44DA-94F6-70065AB46382}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,132 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SpeedBoatLab.Drawings;
using SpeedBoatLab.Entity;
namespace speed_Boat.MovementStrategy
{
public abstract class AbstractStrategy
{
/// <summary>
/// Перемещаемый объект
/// </summary>
private IMovementObject? _movementObject;
/// <summary>
/// Статус перемещения
/// </summary>
private Status _state = Status.NotInit;
/// <summary>
/// Ширина поля
/// </summary>
protected int FieldWidth { get; private set; }
/// <summary>
/// Высота поля
/// </summary>
protected int FieldHeight { get; private set; }
/// <summary>
/// Статус перемещения
/// </summary>
public Status GetStatus()
{
return _state;
}
/// <summary>
/// Установка данных
/// </summary>
public void SetData(IMovementObject moveableObject, int width, int height)
{
if (moveableObject == null)
{
_state = Status.NotInit;
return;
}
_state = Status.InProgress;
_movementObject = moveableObject;
FieldWidth = width;
FieldHeight = height;
}
/// <summary>
/// Шаг перемещения
/// </summary>
public void MakeStep()
{
if (_state != Status.InProgress)
{
return;
}
if (IsTargetDestinaion())
{
_state = Status.Finish;
return;
}
MoveToTarget();
}
/// <summary>
/// Перемещение влево
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false неудача)</returns>
protected bool MoveLeft() => MoveTo(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 => _movementObject?.GetObjectPosition;
/// <summary>
/// Шаг объекта
/// </summary>
/// <returns></returns>
protected int? GetStep()
{
if (_state != Status.InProgress)
{
return null;
}
return _movementObject?.GetStep;
}
/// <summary>
/// Перемещение к цели
/// </summary>
protected abstract void MoveToTarget();
/// <summary>
/// Достигнута ли цель
/// </summary>
/// <returns></returns>
protected abstract bool IsTargetDestinaion();
/// <summary>
/// Попытка перемещения в требуемом направлении
/// </summary>
/// <param name="directionType">Направление</param>
/// <returns>Результат попытки (true - удалось переместиться, false - неудача)</returns>
private bool MoveTo(DirectionType directionType)
{
if (_state != Status.InProgress)
{
return false;
}
if (_movementObject?.CheckCanMove(directionType) ?? false)
{
_movementObject.MoveObject(directionType);
return true;
}
return false;
}
}
}

View File

@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SpeedBoatLab.Drawings;
using SpeedBoatLab.Entity;
namespace speed_Boat.Generics
{
internal class BoatCompareByColor : IComparer<DrawingBoat?>
{
public int Compare(DrawingBoat? x, DrawingBoat? y)
{
// TODO реализовать логику сравнения
if (x == null || x._entityBoat == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y._entityBoat == null)
{
throw new ArgumentNullException(nameof(y));
}
if(x._entityBoat.MainColor.Name != y._entityBoat.MainColor.Name)
{
return x._entityBoat.MainColor.Name.CompareTo(y._entityBoat.MainColor.Name);
}
if(x.GetType().Name == y.GetType().Name && x is DrawingSpeedBoat)
{
EntitySpeedboat _speedboatX = (EntitySpeedboat)x._entityBoat;
EntitySpeedboat _speedboatY = (EntitySpeedboat)y._entityBoat;
if (_speedboatX.SecondColor.Name != _speedboatY.SecondColor.Name)
{
return _speedboatX.SecondColor.Name.CompareTo(_speedboatY.SecondColor.Name);
}
}
var speedCompare = x._entityBoat.Speed.CompareTo(y._entityBoat.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x._entityBoat.Weight.CompareTo(y._entityBoat.Weight);
}
}
}

View File

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SpeedBoatLab.Drawings;
namespace speed_Boat.Generics
{
internal class BoatCompareByType : IComparer<DrawingBoat?>
{
public int Compare(DrawingBoat? x, DrawingBoat? y)
{
if (x == null || x._entityBoat == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y._entityBoat == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x._entityBoat.Speed.CompareTo(y._entityBoat.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x._entityBoat.Weight.CompareTo(y._entityBoat.Weight);
}
}
}

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 speed_Boat.Exceptions
{
[Serializable]
internal class BoatNotFoundException : ApplicationException
{
public BoatNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
public BoatNotFoundException() : base() { }
public BoatNotFoundException(string message) : base(message) { }
public BoatNotFoundException(string message, Exception exception) : base(message, exception){ }
protected BoatNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace speed_Boat.Generics
{
internal class BoatsCollectionInfo : IEquatable<BoatsCollectionInfo>
{
public string Name { get; private set; }
public string Description { get; private set; }
public BoatsCollectionInfo(string name, string description)
{
Name = name;
Description = description;
}
public bool Equals(BoatsCollectionInfo? other)
{
// TODO прописать логику сравнения по свойству Name
if (Name == other?.Name)
return true;
return false;
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}
}

View File

@ -0,0 +1,152 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SpeedBoatLab.Drawings;
using speed_Boat.MovementStrategy;
using System.Drawing;
namespace speed_Boat.Generics
{
internal class BoatsGenericCollection<T, U>
where T : DrawingBoat
where U : IMovementObject
{
/// <summary>
/// Получение объектов коллекции
/// </summary>
public IEnumerable<T?> GetBoats => _collection.GetBoats();
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer"></param>
public void Sort(IComparer<T?> comparer) => _collection.SortSet(comparer);
/// <summary>
/// Ширина окна прорисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна прорисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Размер занимаемого объектом места (ширина)
/// </summary>
private readonly int _placeSizeWidth = 180;
/// <summary>
/// Размер занимаемого объектом места (высота)
/// </summary>
private readonly int _placeSizeHeight = 90;
/// <summary>
/// Набор объектов
/// </summary>
public readonly GenericClass<T> _collection;
/// <summary>
/// Конструктор
/// </summary>
public BoatsGenericCollection(int picWidth, int picHeight)
{
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = new GenericClass<T>(width * height);
}
/// <summary>
/// Перегрузка оператора сложения
/// </summary>
/// <returns></returns>
public static int operator + (BoatsGenericCollection<T, U> collect, T? obj)
{
if (obj != null)
{
return collect?._collection.Insert(obj, new DrawingBoatEquatable()) ?? -1;
}
return 0;
}
/// <summary>
/// Перегрузка оператора вычитания
/// </summary>
public static T? operator - (BoatsGenericCollection<T, U> collect, int pos)//bool??
{
T? obj = collect._collection[pos];
if (obj != null)
{
collect?._collection.Remove(pos);
}
return obj;
}
/// <summary>
/// Получение объекта IMoveableObject
/// </summary>
public U? GetU(int pos)
{
return (U?)_collection[pos]?.GetMoveableObject;
}
/// <summary>
/// Вывод всего набора объектов
/// </summary>
/// <returns></returns>
public Bitmap ShowBoats()
{
Bitmap bmp = new(_pictureWidth, _pictureHeight);
Graphics gr = Graphics.FromImage(bmp);
DrawBackground(gr);
DrawObjects(gr);
return bmp;
}
/// <summary>
/// Метод отрисовки фона
/// </summary>
/// <param name="g"></param>
private void DrawBackground(Graphics g)
{
Pen pen = new(Color.Black, 3);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j)
{
//линия разметки места
g.DrawLine(pen, i * _placeSizeWidth, j *
_placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth / 2, j *
_placeSizeHeight);
}
g.DrawLine(pen, i * _placeSizeWidth, 0, i *
_placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight);
}
}
/// <summary>
/// Метод прорисовки объектов
/// </summary>
/// <param name="g"></param>
private void DrawObjects(Graphics g)
{
int col = 0;
int i = 0;
int width_Col = _pictureWidth / _placeSizeWidth;//количество колонок в окне прорисовки
foreach (var boat in _collection.GetBoats())
{
if(boat != null)
{
boat.screenWidth = _pictureWidth;
boat.screenHeight = _pictureHeight;
boat.SetPosition(col * _placeSizeWidth, (i / width_Col) * _placeSizeHeight);
col++;
if (col > 2)
col = 0;
boat.DrawTransport(g);
i++;
}
else if(boat == null)
{
col++;
if (col > 2)
col = 0;
i++;
continue;
}
}
}
}
}

View File

@ -0,0 +1,194 @@
using speed_Boat.Exceptions;
using speed_Boat.MovementStrategy;
using SpeedBoatLab.Drawings;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace speed_Boat.Generics
{
/// <summary>
/// Класс для хранения коллекции
/// </summary>
internal class BoatsGenericStorage
{
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<BoatsCollectionInfo, BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>> _boatStorages;
///<summary>
/// Возвращение списка названий наборов
/// </summary>
public List<BoatsCollectionInfo> Keys => _boatStorages.Keys.ToList();
///<summary>
/// Ширина окна отрисовки
/// </summary>
private readonly int _pictureWidth;
///<summary>
/// Высота окна отрисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private static readonly char _separatorForKeyValue = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char _separatorRecords = ';';
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
///<summary>
/// Конструктор
/// </summary>
public BoatsGenericStorage(int pictureWidth, int pictureHeight)
{
_boatStorages = new Dictionary<BoatsCollectionInfo, BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
/// <summary>
/// Сохранение информации по катерам в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public void SaveData(string filename)
{
if (_boatStorages.Count == 0)
throw new InvalidOperationException("Невалидная операция: нет данных для сохранения");
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<BoatsCollectionInfo, BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>> record in _boatStorages)
{
StringBuilder records = new();
foreach (DrawingBoat? elem in record.Value.GetBoats)
{
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($"BoatStorage{Environment.NewLine}{data}");
}
}
/// <summary>
/// Загрузка информации по катерам в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
throw new FileNotFoundException("Файл не найден");
using (StreamReader sr = new(filename))
{
if (sr.ReadLine() != "BoatStorage")
throw new FormatException("Неверный формат данных");
string str = sr.ReadLine();
var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
throw new Exception("Нет данных для загрузки");
}
_boatStorages.Clear();
do
{
string[] record = str.Split(_separatorForKeyValue,
StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
str = sr.ReadLine();
continue;
}
BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>
collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawingBoat? boat = elem?.CreateDrawingBoat(_separatorForObject, _pictureWidth, _pictureHeight);
if (boat != null)
{
try { _ = collection + boat; }
catch (BoatNotFoundException e)
{
throw e;
}
catch (StorageOverflowException e)
{
throw e;
}
}
}
_boatStorages.Add(new BoatsCollectionInfo(record[0], string.Empty), collection);
str = sr.ReadLine();
} while (str != null);
}
}
///<summary>
/// Добавление набора
/// </summary>
public void AddSet(string name)
{
if (_boatStorages.ContainsKey(new BoatsCollectionInfo(name, string.Empty)))
{
MessageBox.Show("Словарь уже содержит набор с таким названием", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
_boatStorages.Add(new BoatsCollectionInfo(name, string.Empty), new BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>(_pictureWidth, _pictureHeight));
}
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="name">Название набора</param>
public void DelSet(string name)
{
BoatsGenericCollection<DrawingBoat, DrawingObjectBoat> boat;
if (_boatStorages.TryGetValue(new BoatsCollectionInfo(name, string.Empty), out boat))
{
_boatStorages.Remove(new BoatsCollectionInfo(name, string.Empty));
}
}
/// <summary>
/// Доступ к набору
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public BoatsGenericCollection<DrawingBoat, DrawingObjectBoat>? this[string ind]
{
get
{
BoatsCollectionInfo infBoat = new BoatsCollectionInfo(ind, string.Empty);
if(_boatStorages.ContainsKey(infBoat))
{
return _boatStorages[infBoat];
}
return null;
}
}
}
}

View File

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

View File

@ -0,0 +1,66 @@
using SpeedBoatLab.Drawings;
using SpeedBoatLab.Entity;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace speed_Boat.Generics
{
internal class DrawingBoatEquatable : IEqualityComparer<DrawingBoat?>
{
public bool Equals(DrawingBoat? x, DrawingBoat? y)
{
if (x == null || x._entityBoat == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y._entityBoat == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x._entityBoat.Speed != y._entityBoat.Speed)
{
return false;
}
if (x._entityBoat.Weight != y._entityBoat.Weight)
{
return false;
}
if (x._entityBoat.MainColor != y._entityBoat.MainColor)
{
return false;
}
if (x is DrawingSpeedBoat && y is DrawingSpeedBoat)
{
// TODO доделать логику сравнения дополнительных параметров
EntitySpeedboat _speedboatX = (EntitySpeedboat)x._entityBoat;
EntitySpeedboat _speedboatY = (EntitySpeedboat)y._entityBoat;
if (_speedboatX.isMotor != _speedboatY.isMotor)
{
return false;
}
if (_speedboatX.isProtectedGlass != _speedboatY.isProtectedGlass)
{
return false;
}
if(_speedboatX.SecondColor != _speedboatY.SecondColor)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawingBoat obj)
{
return obj.GetHashCode();
}
}
}

View File

@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SpeedBoatLab.Entity;
using SpeedBoatLab.Drawings;
namespace speed_Boat.MovementStrategy
{
class DrawingObjectBoat : IMovementObject
{
private readonly DrawingBoat? _drawingBoat = null;
public DrawingObjectBoat(DrawingBoat drawingBoat)
{
_drawingBoat = drawingBoat;
}
public ObjectParameters? GetObjectPosition
{
get
{
if(_drawingBoat == null || _drawingBoat._entityBoat == null)
{
return null;
}
return new ObjectParameters(_drawingBoat.GetPoseX, _drawingBoat.GetPoseY, _drawingBoat.GetWidth, _drawingBoat.GetHeight);
}
}
public int GetStep => (int)(_drawingBoat?._entityBoat?.Step ?? 0);
public bool CheckCanMove(DirectionType direction) => _drawingBoat?.CanMove(direction) ?? false;
public void MoveObject(DirectionType direction) => _drawingBoat?.MoveBoat(direction);
}
}

View File

@ -0,0 +1,63 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SpeedBoatLab.Entity;
using System.Drawing;
namespace SpeedBoatLab.Drawings
{
public class DrawingSpeedBoat : DrawingBoat
{
public DrawingSpeedBoat(int speed, double weight, Color mainColor, Color secondColor, bool _isMotor, bool _isProtectedGlass, int width, int height) :
base(speed, weight, mainColor, width, height, 100, 80)
{
if (_entityBoat != null)
{
_entityBoat = new EntitySpeedboat(speed, weight, mainColor, secondColor, _isMotor, _isProtectedGlass);
}
}
/// <summary>
/// перегружаемый метод DrawTransport
/// </summary>
/// <param name="g"></param>
public override void DrawTransport(Graphics g)
{
if (_entityBoat is not EntitySpeedboat speedBoat)
{
return;
}
Point[] points;
Pen pen = new(Color.Black);
Brush additionalBrush = new SolidBrush(speedBoat.SecondColor);
base.DrawTransport(g);
//Защитное стекло
if (speedBoat.isProtectedGlass)
{
points = new Point[]
{
new Point(startXCoord + 70, startYCoord + 25),
new Point(startXCoord + 80, startYCoord + 20),
new Point(startXCoord + 80, startYCoord + 60),
new Point(startXCoord + 70, startYCoord + 55)
};
g.FillPolygon(additionalBrush, points);
g.DrawPolygon(pen, points);
}
//мотор
if (speedBoat.isMotor)
{
g.DrawRectangle(pen, startXCoord + 10, startYCoord + 30, widthBoat - 90, heightBoat - 60);
g.FillRectangle(additionalBrush, startXCoord + 10, startYCoord + 30, widthBoat - 90, heightBoat - 60);
}
}
public void SetExtraColor(Color color)
{
(_entityBoat as EntitySpeedboat).SecondColor = color;
}
}
}

View File

@ -0,0 +1,46 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
namespace SpeedBoatLab.Entity
{
/// <summary>
/// Катер
/// </summary>
public class EntityBoat
{
/// <summary>
/// Скорость катера
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес самого катера
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color MainColor { get; private set; }
/// <summary>
/// Шаг перемещения катера
/// </summary>
public double Step => (double)Speed * 100 / (Weight);
public EntityBoat(int speed, double weight, Color mainColor)
{
Speed = speed;
Weight = weight;
MainColor = mainColor;
}
public void setColor(Color newBaseColor)
{
MainColor = newBaseColor;
}
}
}

View File

@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
namespace SpeedBoatLab.Entity
{
/// <summary>
/// Класс-сущность скоростного катера
/// </summary>
public class EntitySpeedboat : EntityBoat
{
/// <summary>
/// Наличие мотора
/// </summary>
public bool isMotor { get; private set; }
/// <summary>
/// Наличие защитного стекла
/// </summary>
public bool isProtectedGlass { get; private set; }
/// <summary>
/// Доп. цвет
/// </summary>
public Color SecondColor { get; set; }
/// <summary>
/// Параметры катера
/// </summary>
public EntitySpeedboat(int speed, double weight, Color mainColor, Color secondColor, bool _isMotor, bool _isProtectedGlass) :
base(speed, weight, mainColor)
{
isMotor = _isMotor;
isProtectedGlass = _isProtectedGlass;
SecondColor = secondColor;
}
public void ChangeDopColor(Color newDopColor)
{
SecondColor = newDopColor;
}
}
}

View File

@ -0,0 +1,65 @@
using SpeedBoatLab.Entity;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpeedBoatLab.Drawings
{
public static class ExtentionBoat
{
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <param name="separatorForObject">Разделитель данных</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
/// <returns>Объект</returns>
public static DrawingBoat? CreateDrawingBoat(this string info, char separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawingBoat(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
}
if (strs.Length == 6)
{
return new DrawingSpeedBoat(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;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningCar">Сохраняемый объект</param>
/// <param name="separatorForObject">Разделитель данных</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawingBoat drawingBoat, char separatorForObject)
{
var boat = drawingBoat._entityBoat;
if (boat == null)
{
return string.Empty;
}
var str =
$"{boat.Speed}{separatorForObject}{boat.Weight}{separatorForObject}{boat.MainColor.Name}";
if (boat is not EntitySpeedboat speedBoat)
{
return str;
}
return
$"{str}{separatorForObject}{speedBoat.SecondColor.Name}{separatorForObject}" +
$"{speedBoat.isMotor}{separatorForObject}{speedBoat.isProtectedGlass}";
}
}
}

View File

@ -0,0 +1,298 @@

namespace SpeedBoatLab
{
partial class FormBoatCollection
{
/// <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()
{
groupBox1 = new System.Windows.Forms.GroupBox();
groupBox3 = new System.Windows.Forms.GroupBox();
button1 = new System.Windows.Forms.Button();
button2 = new System.Windows.Forms.Button();
groupBox2 = new System.Windows.Forms.GroupBox();
deleteStorageButton = new System.Windows.Forms.Button();
storagesListBox = new System.Windows.Forms.ListBox();
addStorageButton = new System.Windows.Forms.Button();
nameStorageTextBox = new System.Windows.Forms.TextBox();
label1 = new System.Windows.Forms.Label();
maskedTextBoxNumber = new System.Windows.Forms.MaskedTextBox();
UpdateCollectionButton = new System.Windows.Forms.Button();
DeleteBoatButton = new System.Windows.Forms.Button();
AddBoatButton = new System.Windows.Forms.Button();
menuStrip1 = new System.Windows.Forms.MenuStrip();
файлToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
загрузкаToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
сохранениеToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
pictureBoxCollection = new System.Windows.Forms.PictureBox();
openFileDialog = new System.Windows.Forms.OpenFileDialog();
saveFileDialog = new System.Windows.Forms.SaveFileDialog();
groupBox1.SuspendLayout();
groupBox3.SuspendLayout();
groupBox2.SuspendLayout();
menuStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
SuspendLayout();
//
// groupBox1
//
groupBox1.Controls.Add(groupBox3);
groupBox1.Controls.Add(groupBox2);
groupBox1.Controls.Add(label1);
groupBox1.Controls.Add(maskedTextBoxNumber);
groupBox1.Controls.Add(UpdateCollectionButton);
groupBox1.Controls.Add(DeleteBoatButton);
groupBox1.Controls.Add(AddBoatButton);
groupBox1.Controls.Add(menuStrip1);
groupBox1.Location = new System.Drawing.Point(581, 2);
groupBox1.Name = "groupBox1";
groupBox1.Size = new System.Drawing.Size(205, 586);
groupBox1.TabIndex = 0;
groupBox1.TabStop = false;
groupBox1.Text = "Настройки";
//
// groupBox3
//
groupBox3.Controls.Add(button1);
groupBox3.Controls.Add(button2);
groupBox3.Location = new System.Drawing.Point(6, 439);
groupBox3.Name = "groupBox3";
groupBox3.Size = new System.Drawing.Size(193, 102);
groupBox3.TabIndex = 7;
groupBox3.TabStop = false;
groupBox3.Text = "Сортировки";
//
// button1
//
button1.Location = new System.Drawing.Point(6, 61);
button1.Name = "button1";
button1.Size = new System.Drawing.Size(181, 29);
button1.TabIndex = 7;
button1.Text = "Сортировка по типу";
button1.UseVisualStyleBackColor = true;
button1.Click += ButtonSortByType_Click;
//
// button2
//
button2.Location = new System.Drawing.Point(6, 26);
button2.Name = "button2";
button2.Size = new System.Drawing.Size(181, 29);
button2.TabIndex = 8;
button2.Text = "Сортировка по цвету";
button2.UseVisualStyleBackColor = true;
button2.Click += ButtonSortByColor_Click;
//
// groupBox2
//
groupBox2.Controls.Add(deleteStorageButton);
groupBox2.Controls.Add(storagesListBox);
groupBox2.Controls.Add(addStorageButton);
groupBox2.Controls.Add(nameStorageTextBox);
groupBox2.Location = new System.Drawing.Point(6, 22);
groupBox2.Name = "groupBox2";
groupBox2.Size = new System.Drawing.Size(193, 240);
groupBox2.TabIndex = 5;
groupBox2.TabStop = false;
groupBox2.Text = "Наборы";
//
// deleteStorageButton
//
deleteStorageButton.Location = new System.Drawing.Point(6, 205);
deleteStorageButton.Name = "deleteStorageButton";
deleteStorageButton.Size = new System.Drawing.Size(181, 29);
deleteStorageButton.TabIndex = 5;
deleteStorageButton.Text = "Удалить набор";
deleteStorageButton.UseVisualStyleBackColor = true;
deleteStorageButton.Click += deleteStorageButton_Click;
//
// storagesListBox
//
storagesListBox.FormattingEnabled = true;
storagesListBox.ItemHeight = 20;
storagesListBox.Location = new System.Drawing.Point(6, 94);
storagesListBox.Name = "storagesListBox";
storagesListBox.Size = new System.Drawing.Size(181, 104);
storagesListBox.TabIndex = 4;
storagesListBox.SelectedIndexChanged += storageListBox_SelectedIndexChanged;
//
// addStorageButton
//
addStorageButton.Location = new System.Drawing.Point(6, 59);
addStorageButton.Name = "addStorageButton";
addStorageButton.Size = new System.Drawing.Size(181, 29);
addStorageButton.TabIndex = 3;
addStorageButton.Text = "Добавить набор";
addStorageButton.UseVisualStyleBackColor = true;
addStorageButton.Click += storageAddButton_Click;
//
// nameStorageTextBox
//
nameStorageTextBox.Location = new System.Drawing.Point(6, 26);
nameStorageTextBox.Name = "nameStorageTextBox";
nameStorageTextBox.Size = new System.Drawing.Size(181, 27);
nameStorageTextBox.TabIndex = 2;
//
// label1
//
label1.AutoSize = true;
label1.Location = new System.Drawing.Point(6, 308);
label1.Name = "label1";
label1.Size = new System.Drawing.Size(135, 20);
label1.TabIndex = 4;
label1.Text = "введите позицию:";
//
// maskedTextBoxNumber
//
maskedTextBoxNumber.Location = new System.Drawing.Point(6, 331);
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new System.Drawing.Size(193, 27);
maskedTextBoxNumber.TabIndex = 3;
//
// UpdateCollectionButton
//
UpdateCollectionButton.Location = new System.Drawing.Point(6, 400);
UpdateCollectionButton.Name = "UpdateCollectionButton";
UpdateCollectionButton.Size = new System.Drawing.Size(193, 29);
UpdateCollectionButton.TabIndex = 2;
UpdateCollectionButton.Text = "Обновить коллекцию";
UpdateCollectionButton.UseVisualStyleBackColor = true;
UpdateCollectionButton.Click += ButtonRefreshCollection_Click;
//
// DeleteBoatButton
//
DeleteBoatButton.Location = new System.Drawing.Point(6, 364);
DeleteBoatButton.Name = "DeleteBoatButton";
DeleteBoatButton.Size = new System.Drawing.Size(193, 30);
DeleteBoatButton.TabIndex = 1;
DeleteBoatButton.Text = "Удалить Катер";
DeleteBoatButton.UseVisualStyleBackColor = true;
DeleteBoatButton.Click += ButtonRemoveBoat_Click;
//
// AddBoatButton
//
AddBoatButton.Location = new System.Drawing.Point(6, 277);
AddBoatButton.Name = "AddBoatButton";
AddBoatButton.Size = new System.Drawing.Size(193, 28);
AddBoatButton.TabIndex = 0;
AddBoatButton.Text = "Добавить Катер";
AddBoatButton.UseVisualStyleBackColor = true;
AddBoatButton.Click += ButtonAddBoat_Click;
//
// menuStrip1
//
menuStrip1.Dock = System.Windows.Forms.DockStyle.Bottom;
menuStrip1.ImageScalingSize = new System.Drawing.Size(20, 20);
menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { файлToolStripMenuItem });
menuStrip1.Location = new System.Drawing.Point(3, 555);
menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new System.Drawing.Size(199, 28);
menuStrip1.TabIndex = 6;
menuStrip1.Text = "menuStrip";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { загрузкаToolStripMenuItem, сохранениеToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new System.Drawing.Size(59, 24);
файлToolStripMenuItem.Text = "Файл";
//
// загрузкаToolStripMenuItem
//
загрузкаToolStripMenuItem.Name = агрузкаToolStripMenuItem";
загрузкаToolStripMenuItem.Size = new System.Drawing.Size(177, 26);
загрузкаToolStripMenuItem.Text = "Загрузка";
загрузкаToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// сохранениеToolStripMenuItem
//
сохранениеToolStripMenuItem.Name = "сохранениеToolStripMenuItem";
сохранениеToolStripMenuItem.Size = new System.Drawing.Size(177, 26);
сохранениеToolStripMenuItem.Text = "Сохранение";
сохранениеToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// pictureBoxCollection
//
pictureBoxCollection.Location = new System.Drawing.Point(12, 12);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new System.Drawing.Size(554, 576);
pictureBoxCollection.TabIndex = 1;
pictureBoxCollection.TabStop = false;
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog1";
openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// FormBoatCollection
//
AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
ClientSize = new System.Drawing.Size(800, 600);
Controls.Add(pictureBoxCollection);
Controls.Add(groupBox1);
MainMenuStrip = menuStrip1;
Name = "FormBoatCollection";
Text = "Коллекция катеров";
groupBox1.ResumeLayout(false);
groupBox1.PerformLayout();
groupBox3.ResumeLayout(false);
groupBox2.ResumeLayout(false);
groupBox2.PerformLayout();
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
ResumeLayout(false);
}
#endregion
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Button UpdateCollectionButton;
private System.Windows.Forms.Button DeleteBoatButton;
private System.Windows.Forms.Button AddBoatButton;
private System.Windows.Forms.PictureBox pictureBoxCollection;
private System.Windows.Forms.MaskedTextBox maskedTextBoxNumber;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.ListBox storagesListBox;
private System.Windows.Forms.Button addStorageButton;
private System.Windows.Forms.TextBox nameStorageTextBox;
private System.Windows.Forms.Button deleteStorageButton;
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem файлToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem загрузкаToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem сохранениеToolStripMenuItem;
private System.Windows.Forms.OpenFileDialog openFileDialog;
private System.Windows.Forms.SaveFileDialog saveFileDialog;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
}
}

View File

@ -0,0 +1,375 @@
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 SpeedBoatLab.Drawings;
using speed_Boat.Generics;
using speed_Boat.MovementStrategy;
using speed_Boat;
using Microsoft.Extensions.Logging;
using speed_Boat.Exceptions;
namespace SpeedBoatLab
{
public partial class FormBoatCollection : Form
{
/// <summary>
/// Набор объектов
/// </summary>
private readonly BoatsGenericStorage _storage;
/// <summary>
/// Логгер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormBoatCollection(ILogger<FormBoatCollection> logger)
{
InitializeComponent();
_storage = new BoatsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
}
///<summary>
/// Заполнение collectionsListBox
/// </summary>
private void ReloadObjects()
{
int index = storagesListBox.SelectedIndex;
storagesListBox.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++)
{
storagesListBox.Items.Add(_storage.Keys[i].Name);
}
if (storagesListBox.Items.Count > 0 && (index == -1 ||
index >= storagesListBox.Items.Count))
{
storagesListBox.SelectedIndex = 0;
}
else if (storagesListBox.Items.Count > 0 && index > -1 &&
index < storagesListBox.Items.Count)
{
storagesListBox.SelectedIndex = index;
}
}
///<summary>
/// Добавление набора в коллекцию
/// </summary>
private void storageAddButton_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(nameStorageTextBox.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_storage.AddSet(nameStorageTextBox.Text);
ReloadObjects();
_logger.LogInformation($"Добавлен набор: {nameStorageTextBox.Text}");
}
///<summary>
/// Выбор набора
/// </summary>
private void storageListBox_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBoxCollection.Image =
_storage[storagesListBox.SelectedItem?.ToString() ?? string.Empty]?.ShowBoats();
}
///<storage>
/// Удаление набора
/// </storage>
private void deleteStorageButton_Click(Object sender, EventArgs e)
{
if (storagesListBox.SelectedIndex == -1)
{
_logger.LogWarning("Набор для удаления не выбран");
return;
}
string name = storagesListBox.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Удалить объект {storagesListBox.SelectedItem}?",
"Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(storagesListBox.SelectedItem.ToString() ?? string.Empty);
ReloadObjects();
_logger.LogInformation($"Удален набор: {name}");
}
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddBoat_Click(object sender, EventArgs e)
{
if (storagesListBox.SelectedIndex == -1)
{
return;
}
var obj = _storage[storagesListBox.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
FormBoatConfig form = new();
form.Show();
Action<DrawingBoat>? boatDelegate = new((boat) =>
{
try
{
_ = obj + boat;
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Добавлен объект в коллекцию {storagesListBox.SelectedItem.ToString() ?? string.Empty}");
pictureBoxCollection.Image = obj.ShowBoats();
}
catch (StorageOverflowException ex)
{
_logger.LogWarning($"Коллекция {storagesListBox.SelectedItem.ToString() ?? string.Empty} переполнена");
MessageBox.Show(ex.Message);
}
catch (ArgumentException ex)
{
_logger.LogWarning($"Добавляемый объект уже существует в коллекции {storagesListBox.SelectedItem.ToString() ?? string.Empty}");
MessageBox.Show("Добавляемый объект уже сущесвует в коллекции");
}
});
form.AddEvent(boatDelegate);
/* if (storagesListBox.SelectedIndex == -1)
{
_logger.LogWarning("Набор для добавления обьекта не выбран");
return;
}
var FormBoatConfig = new FormBoatConfig();
FormBoatConfig.Show();
FormBoatConfig.AddEvent(new(AddBoat));*/
}
/* public void AddBoat(DrawingBoat? boat)
{
if (storagesListBox.SelectedIndex == -1)
{
_logger.LogWarning("Набор для удаления не выбран");
return;
}
var obj = _storage[storagesListBox.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
_logger.LogWarning("Добавление пустого обьекта");
return;
}
try
{
_ = obj + boat;
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Добавлен объект в набор {storagesListBox.SelectedItem.ToString() ?? string.Empty}");
pictureBoxCollection.Image = obj.ShowBoats();
}
catch (StorageOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning($"{ex.Message} в наборе {storagesListBox.SelectedItem.ToString() ?? string.Empty}");
}
catch (ArgumentException ex)
{
MessageBox.Show("Добавляемый объект уже существует в коллекции");
_logger.LogWarning($"Добавляемый объект уже существует в коллекции {storagesListBox.SelectedItem.ToString() ?? string.Empty}");
}
}*/
/// <summary>
/// Удаление объекта из набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveBoat_Click(object sender, EventArgs e)
{
if (storagesListBox.SelectedIndex == -1)
{
_logger.LogWarning("Удаление объекта из несуществующего набора");
return;
}
var obj = _storage[storagesListBox.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
string insertPosition = maskedTextBoxNumber.Text;
int pos = -1;
if (insertPosition != string.Empty)
{
int.TryParse(insertPosition, out pos);
if (pos < 0 || pos > obj._collection.Count - 1)
{
MessageBox.Show("Неверный формат позиции");
_logger.LogWarning($"Неверный формат позиции:{pos}");
}
try
{
if (obj - pos != null)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowBoats();
_logger.LogInformation($"Удален объект из набора {storagesListBox.SelectedItem.ToString()}");
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogInformation($"Не удалось удалить объект из набора {storagesListBox.SelectedItem.ToString()}");
}
}
catch (BoatNotFoundException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"{ex.Message} из набора {storagesListBox.SelectedItem.ToString()}");
}
}
else if (insertPosition == string.Empty)
{
MessageBox.Show("Неверный формат позиции");
_logger.LogWarning($"Неверный формат позиции:{insertPosition}");
}
}
/// <summary>
/// Обновление рисунка по набору
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
{
if (storagesListBox.SelectedIndex == -1)
{
return;
}
var obj = _storage[storagesListBox.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
pictureBoxCollection.Image = obj.ShowBoats();
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Сохранение наборов в файл {saveFileDialog.FileName} прошло успешно:");
}
catch (Exception ex)
{
MessageBox.Show($"Не сохранилось: {ex.Message}",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не удалось сохранить наборы: {ex.Message}");
}
}
}
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.LoadData(saveFileDialog.FileName);
ReloadObjects();
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Загрузились наборы из файла {openFileDialog.FileName}");
}
catch (Exception ex)
{
MessageBox.Show($"Не удалось загрузить: {ex.Message}",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не удалось сохранить наборы с ошибкой: {ex.Message}");
}
}
}
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByType_Click(object sender, EventArgs e) => CompareBoats(new BoatCompareByType());
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByColor_Click(object sender, EventArgs e) => CompareBoats(new BoatCompareByColor());
private void CompareStorages(IComparer<BoatsGenericStorage?> comparer, string name1, string name2)
{
if (storagesListBox.Items.Count < 2)
{
return;
}
var _storage1 = _storage[name1];
var _storage2 = _storage[name2];
if (_storage1 == null || _storage2 == null)
return;
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer"></param>
private void CompareBoats(IComparer<DrawingBoat?> comparer)
{
if (storagesListBox.SelectedIndex == -1)
{
return;
}
var obj = _storage[storagesListBox.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
obj.Sort(comparer);
pictureBoxCollection.Image = obj.ShowBoats();
}
}
}

View File

@ -0,0 +1,129 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="menuStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>153, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>323, 17</value>
</metadata>
</root>

View File

@ -0,0 +1,389 @@
namespace speed_Boat
{
partial class FormBoatConfig
{
/// <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()
{
groupBox1 = new System.Windows.Forms.GroupBox();
labelModifyedObject = new System.Windows.Forms.Label();
labelSimpleObject = new System.Windows.Forms.Label();
checkBoxIsProtectedGlass = new System.Windows.Forms.CheckBox();
checkBoxIsMotor = new System.Windows.Forms.CheckBox();
groupBox2 = new System.Windows.Forms.GroupBox();
panelWhite = new System.Windows.Forms.Panel();
panelYellow = new System.Windows.Forms.Panel();
panelGray = new System.Windows.Forms.Panel();
panelBlue = new System.Windows.Forms.Panel();
panelGreen = new System.Windows.Forms.Panel();
panelPurple = new System.Windows.Forms.Panel();
panelRed = new System.Windows.Forms.Panel();
panelBlack = new System.Windows.Forms.Panel();
numericUpDownWeight = new System.Windows.Forms.NumericUpDown();
numericUpDownSpeed = new System.Windows.Forms.NumericUpDown();
label2 = new System.Windows.Forms.Label();
label1 = new System.Windows.Forms.Label();
panelobject = new System.Windows.Forms.Panel();
LabelDopColor = new System.Windows.Forms.Label();
LabelBaseColor = new System.Windows.Forms.Label();
pictureBoxObject = new System.Windows.Forms.PictureBox();
buttonCancel = new System.Windows.Forms.Button();
buttonOk = new System.Windows.Forms.Button();
groupBox1.SuspendLayout();
groupBox2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
panelobject.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
SuspendLayout();
//
// groupBox1
//
groupBox1.Controls.Add(labelModifyedObject);
groupBox1.Controls.Add(labelSimpleObject);
groupBox1.Controls.Add(checkBoxIsProtectedGlass);
groupBox1.Controls.Add(checkBoxIsMotor);
groupBox1.Controls.Add(groupBox2);
groupBox1.Controls.Add(numericUpDownWeight);
groupBox1.Controls.Add(numericUpDownSpeed);
groupBox1.Controls.Add(label2);
groupBox1.Controls.Add(label1);
groupBox1.Location = new System.Drawing.Point(12, 12);
groupBox1.Name = "groupBox1";
groupBox1.Size = new System.Drawing.Size(316, 426);
groupBox1.TabIndex = 0;
groupBox1.TabStop = false;
groupBox1.Text = "Параметры";
//
// labelModifyedObject
//
labelModifyedObject.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
labelModifyedObject.Location = new System.Drawing.Point(156, 370);
labelModifyedObject.Name = "labelModifyedObject";
labelModifyedObject.RightToLeft = System.Windows.Forms.RightToLeft.No;
labelModifyedObject.Size = new System.Drawing.Size(114, 30);
labelModifyedObject.TabIndex = 12;
labelModifyedObject.Text = "Продвинутый";
labelModifyedObject.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
labelModifyedObject.MouseDown += labelSimpleObject_MouseDown;
//
// labelSimpleObject
//
labelSimpleObject.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
labelSimpleObject.Location = new System.Drawing.Point(35, 370);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new System.Drawing.Size(114, 30);
labelSimpleObject.TabIndex = 11;
labelSimpleObject.Text = "Простой";
labelSimpleObject.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
labelSimpleObject.MouseDown += labelSimpleObject_MouseDown;
//
// checkBoxIsProtectedGlass
//
checkBoxIsProtectedGlass.AutoSize = true;
checkBoxIsProtectedGlass.Location = new System.Drawing.Point(20, 152);
checkBoxIsProtectedGlass.Name = "checkBoxIsProtectedGlass";
checkBoxIsProtectedGlass.Size = new System.Drawing.Size(281, 24);
checkBoxIsProtectedGlass.TabIndex = 10;
checkBoxIsProtectedGlass.Text = "Признак наличия защитного стекла";
checkBoxIsProtectedGlass.UseVisualStyleBackColor = true;
//
// checkBoxIsMotor
//
checkBoxIsMotor.AutoSize = true;
checkBoxIsMotor.Location = new System.Drawing.Point(20, 122);
checkBoxIsMotor.Name = "checkBoxIsMotor";
checkBoxIsMotor.Size = new System.Drawing.Size(210, 24);
checkBoxIsMotor.TabIndex = 9;
checkBoxIsMotor.Text = "Признак наличия мотора";
checkBoxIsMotor.UseVisualStyleBackColor = true;
//
// groupBox2
//
groupBox2.Controls.Add(panelWhite);
groupBox2.Controls.Add(panelYellow);
groupBox2.Controls.Add(panelGray);
groupBox2.Controls.Add(panelBlue);
groupBox2.Controls.Add(panelGreen);
groupBox2.Controls.Add(panelPurple);
groupBox2.Controls.Add(panelRed);
groupBox2.Controls.Add(panelBlack);
groupBox2.Location = new System.Drawing.Point(20, 183);
groupBox2.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
groupBox2.Name = "groupBox2";
groupBox2.Padding = new System.Windows.Forms.Padding(3, 4, 3, 4);
groupBox2.Size = new System.Drawing.Size(261, 173);
groupBox2.TabIndex = 8;
groupBox2.TabStop = false;
groupBox2.Text = "Цвета";
//
// panelWhite
//
panelWhite.AllowDrop = true;
panelWhite.BackColor = System.Drawing.Color.White;
panelWhite.Location = new System.Drawing.Point(191, 104);
panelWhite.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
panelWhite.Name = "panelWhite";
panelWhite.Size = new System.Drawing.Size(50, 50);
panelWhite.TabIndex = 3;
panelWhite.MouseDown += PanelColor_MouseDown;
//
// panelYellow
//
panelYellow.AllowDrop = true;
panelYellow.BackColor = System.Drawing.Color.Yellow;
panelYellow.Location = new System.Drawing.Point(191, 37);
panelYellow.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
panelYellow.Name = "panelYellow";
panelYellow.Size = new System.Drawing.Size(50, 50);
panelYellow.TabIndex = 1;
panelYellow.MouseDown += PanelColor_MouseDown;
//
// panelGray
//
panelGray.AllowDrop = true;
panelGray.BackColor = System.Drawing.Color.Gray;
panelGray.Location = new System.Drawing.Point(135, 104);
panelGray.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
panelGray.Name = "panelGray";
panelGray.Size = new System.Drawing.Size(50, 50);
panelGray.TabIndex = 4;
panelGray.MouseDown += PanelColor_MouseDown;
//
// panelBlue
//
panelBlue.AllowDrop = true;
panelBlue.BackColor = System.Drawing.Color.Blue;
panelBlue.Location = new System.Drawing.Point(79, 104);
panelBlue.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
panelBlue.Name = "panelBlue";
panelBlue.Size = new System.Drawing.Size(50, 50);
panelBlue.TabIndex = 5;
panelBlue.MouseDown += PanelColor_MouseDown;
//
// panelGreen
//
panelGreen.AllowDrop = true;
panelGreen.BackColor = System.Drawing.Color.Green;
panelGreen.Location = new System.Drawing.Point(135, 37);
panelGreen.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
panelGreen.Name = "panelGreen";
panelGreen.Size = new System.Drawing.Size(50, 50);
panelGreen.TabIndex = 1;
panelGreen.MouseDown += PanelColor_MouseDown;
//
// panelPurple
//
panelPurple.AllowDrop = true;
panelPurple.BackColor = System.Drawing.Color.Purple;
panelPurple.Location = new System.Drawing.Point(23, 104);
panelPurple.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
panelPurple.Name = "panelPurple";
panelPurple.Size = new System.Drawing.Size(50, 50);
panelPurple.TabIndex = 2;
panelPurple.MouseDown += PanelColor_MouseDown;
//
// panelRed
//
panelRed.AllowDrop = true;
panelRed.BackColor = System.Drawing.Color.Red;
panelRed.Location = new System.Drawing.Point(79, 37);
panelRed.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
panelRed.Name = "panelRed";
panelRed.Size = new System.Drawing.Size(50, 50);
panelRed.TabIndex = 1;
panelRed.MouseDown += PanelColor_MouseDown;
//
// panelBlack
//
panelBlack.AllowDrop = true;
panelBlack.BackColor = System.Drawing.Color.Black;
panelBlack.Location = new System.Drawing.Point(23, 37);
panelBlack.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
panelBlack.Name = "panelBlack";
panelBlack.Size = new System.Drawing.Size(50, 50);
panelBlack.TabIndex = 0;
panelBlack.MouseDown += PanelColor_MouseDown;
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new System.Drawing.Point(98, 77);
numericUpDownWeight.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
numericUpDownWeight.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownWeight.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownWeight.Name = "numericUpDownWeight";
numericUpDownWeight.Size = new System.Drawing.Size(137, 27);
numericUpDownWeight.TabIndex = 7;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new System.Drawing.Point(98, 38);
numericUpDownSpeed.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
numericUpDownSpeed.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownSpeed.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownSpeed.Name = "numericUpDownSpeed";
numericUpDownSpeed.Size = new System.Drawing.Size(137, 27);
numericUpDownSpeed.TabIndex = 6;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// label2
//
label2.AutoSize = true;
label2.Location = new System.Drawing.Point(20, 79);
label2.Name = "label2";
label2.Size = new System.Drawing.Size(36, 20);
label2.TabIndex = 5;
label2.Text = "Вес:";
//
// label1
//
label1.AutoSize = true;
label1.Location = new System.Drawing.Point(20, 41);
label1.Name = "label1";
label1.Size = new System.Drawing.Size(76, 20);
label1.TabIndex = 4;
label1.Text = "Скорость:";
//
// panelobject
//
panelobject.AllowDrop = true;
panelobject.Controls.Add(LabelDopColor);
panelobject.Controls.Add(LabelBaseColor);
panelobject.Controls.Add(pictureBoxObject);
panelobject.Location = new System.Drawing.Point(334, 22);
panelobject.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
panelobject.Name = "panelobject";
panelobject.Size = new System.Drawing.Size(272, 346);
panelobject.TabIndex = 11;
panelobject.DragDrop += panelobject_DragDrop;
panelobject.DragEnter += panelobject_DragEnter;
//
// LabelDopColor
//
LabelDopColor.AllowDrop = true;
LabelDopColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
LabelDopColor.Location = new System.Drawing.Point(142, 21);
LabelDopColor.Name = "LabelDopColor";
LabelDopColor.Size = new System.Drawing.Size(114, 30);
LabelDopColor.TabIndex = 3;
LabelDopColor.Text = "Доп.цвет";
LabelDopColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
LabelDopColor.DragDrop += LabelDopColor_DragDrop;
LabelDopColor.DragEnter += LabelDopColor_DragEnter;
//
// LabelBaseColor
//
LabelBaseColor.AllowDrop = true;
LabelBaseColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
LabelBaseColor.Location = new System.Drawing.Point(14, 21);
LabelBaseColor.Name = "LabelBaseColor";
LabelBaseColor.Size = new System.Drawing.Size(114, 30);
LabelBaseColor.TabIndex = 2;
LabelBaseColor.Text = "Цвет";
LabelBaseColor.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
LabelBaseColor.DragDrop += LabelBaseColor_DragDrop;
LabelBaseColor.DragEnter += LabelBaseColor_DragEnter;
//
// pictureBoxObject
//
pictureBoxObject.Location = new System.Drawing.Point(14, 69);
pictureBoxObject.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new System.Drawing.Size(242, 258);
pictureBoxObject.TabIndex = 1;
pictureBoxObject.TabStop = false;
//
// buttonCancel
//
buttonCancel.Location = new System.Drawing.Point(504, 381);
buttonCancel.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new System.Drawing.Size(86, 31);
buttonCancel.TabIndex = 14;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
//
// buttonOk
//
buttonOk.Location = new System.Drawing.Point(348, 381);
buttonOk.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
buttonOk.Name = "buttonOk";
buttonOk.Size = new System.Drawing.Size(86, 31);
buttonOk.TabIndex = 13;
buttonOk.Text = "Добавить";
buttonOk.UseVisualStyleBackColor = true;
buttonOk.Click += buttonOk_Click;
//
// FormBoatConfig
//
AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
ClientSize = new System.Drawing.Size(634, 450);
Controls.Add(buttonCancel);
Controls.Add(buttonOk);
Controls.Add(panelobject);
Controls.Add(groupBox1);
Name = "FormBoatConfig";
Text = "Создание объекта";
groupBox1.ResumeLayout(false);
groupBox1.PerformLayout();
groupBox2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).EndInit();
panelobject.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)pictureBoxObject).EndInit();
ResumeLayout(false);
}
#endregion
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.NumericUpDown numericUpDownWeight;
private System.Windows.Forms.NumericUpDown numericUpDownSpeed;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label labelModifyedObject;
private System.Windows.Forms.Label labelSimpleObject;
private System.Windows.Forms.CheckBox checkBoxIsProtectedGlass;
private System.Windows.Forms.CheckBox checkBoxIsMotor;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.Panel panelWhite;
private System.Windows.Forms.Panel panelYellow;
private System.Windows.Forms.Panel panelGray;
private System.Windows.Forms.Panel panelBlue;
private System.Windows.Forms.Panel panelGreen;
private System.Windows.Forms.Panel panelPurple;
private System.Windows.Forms.Panel panelRed;
private System.Windows.Forms.Panel panelBlack;
private System.Windows.Forms.Panel panelobject;
private System.Windows.Forms.Label LabelDopColor;
private System.Windows.Forms.Label LabelBaseColor;
private System.Windows.Forms.PictureBox pictureBoxObject;
private System.Windows.Forms.Button buttonCancel;
private System.Windows.Forms.Button buttonOk;
}
}

View File

@ -0,0 +1,146 @@
using SpeedBoatLab.Drawings;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace speed_Boat
{
public partial class FormBoatConfig : Form
{
private event Action<DrawingBoat> EventAddBoat;
DrawingBoat _boat = null;
public FormBoatConfig()
{
InitializeComponent();
panelBlack.MouseDown += PanelColor_MouseDown;
panelPurple.MouseDown += PanelColor_MouseDown;
panelGray.MouseDown += PanelColor_MouseDown;
panelGreen.MouseDown += PanelColor_MouseDown;
panelRed.MouseDown += PanelColor_MouseDown;
panelWhite.MouseDown += PanelColor_MouseDown;
panelYellow.MouseDown += PanelColor_MouseDown;
panelBlue.MouseDown += PanelColor_MouseDown;
buttonCancel.Click += (s, a) => Close();
}
public void AddEvent(Action<DrawingBoat> ev)
{
if (EventAddBoat == null)
{
EventAddBoat = new Action<DrawingBoat>(ev);
}
else
{
EventAddBoat += ev;
}
}
private void DrawBoat()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_boat?.SetPosition(5, 5);
_boat?.DrawTransport(gr);
pictureBoxObject.Image = bmp;
}
private void labelSimpleObject_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))
{
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 "labelSimpleObject":
_boat = new DrawingBoat((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, pictureBoxObject.Width,
pictureBoxObject.Height);
break;
case "labelModifyedObject":
_boat = new DrawingSpeedBoat((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, Color.Black, checkBoxIsMotor.Checked,
checkBoxIsProtectedGlass.Checked, pictureBoxObject.Width,
pictureBoxObject.Height);
break;
}
DrawBoat();
}
private void buttonOk_Click(object sender, EventArgs e)
{
EventAddBoat?.Invoke(_boat);
Close();
}
private void PanelColor_MouseDown(object sender, MouseEventArgs e)
{
(sender as Control).DoDragDrop((sender as Control).BackColor, DragDropEffects.Move | DragDropEffects.Copy);
}
private void LabelBaseColor_DragDrop(object sender, DragEventArgs e)
{
if (_boat != null)
{
_boat.SetBodyColor((Color)e.Data.GetData(typeof(Color)));
DrawBoat();
}
else return;
}
private void LabelDopColor_DragDrop(object sender, DragEventArgs e)
{
if (_boat is not DrawingSpeedBoat MotorBoat || _boat == null)
{
return;
}
MotorBoat.SetExtraColor((Color)e.Data.GetData(typeof(Color)));
DrawBoat();
}
private void LabelBaseColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void LabelDopColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Color)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
}
}

View File

@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
@ -26,36 +26,36 @@
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->

View File

@ -0,0 +1,207 @@

namespace SpeedBoatLab
{
partial class FormSpeedBoat
{
/// <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()
{
pictureBoxSpeedBoat = new System.Windows.Forms.PictureBox();
buttonCreate = new System.Windows.Forms.Button();
buttonUp = new System.Windows.Forms.Button();
buttonLeft = new System.Windows.Forms.Button();
buttonDown = new System.Windows.Forms.Button();
buttonRight = new System.Windows.Forms.Button();
comboBox1 = new System.Windows.Forms.ComboBox();
StepButton = new System.Windows.Forms.Button();
buttonCreateSpeedBoat = new System.Windows.Forms.Button();
mainColorDialog = new System.Windows.Forms.ColorDialog();
additionalColorDialog = new System.Windows.Forms.ColorDialog();
BoatSelectButton = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)pictureBoxSpeedBoat).BeginInit();
SuspendLayout();
//
// pictureBoxSpeedBoat
//
pictureBoxSpeedBoat.Dock = System.Windows.Forms.DockStyle.Fill;
pictureBoxSpeedBoat.Location = new System.Drawing.Point(0, 0);
pictureBoxSpeedBoat.Name = "pictureBoxSpeedBoat";
pictureBoxSpeedBoat.Size = new System.Drawing.Size(800, 450);
pictureBoxSpeedBoat.TabIndex = 0;
pictureBoxSpeedBoat.TabStop = false;
//
// buttonCreate
//
buttonCreate.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left;
buttonCreate.BackColor = System.Drawing.Color.White;
buttonCreate.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
buttonCreate.Location = new System.Drawing.Point(12, 387);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new System.Drawing.Size(103, 51);
buttonCreate.TabIndex = 2;
buttonCreate.Text = "Создать катер";
buttonCreate.UseVisualStyleBackColor = false;
buttonCreate.Click += buttonCreate_Click;
//
// buttonUp
//
buttonUp.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right;
buttonUp.BackgroundImage = speed_Boat.Properties.Resources.UP;
buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
buttonUp.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
buttonUp.Location = new System.Drawing.Point(716, 372);
buttonUp.Name = "buttonUp";
buttonUp.Size = new System.Drawing.Size(30, 30);
buttonUp.TabIndex = 10;
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += buttonMove_Click;
//
// buttonLeft
//
buttonLeft.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right;
buttonLeft.BackgroundImage = speed_Boat.Properties.Resources.LEFT;
buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
buttonLeft.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
buttonLeft.Location = new System.Drawing.Point(680, 408);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new System.Drawing.Size(30, 30);
buttonLeft.TabIndex = 9;
buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.Click += buttonMove_Click;
//
// buttonDown
//
buttonDown.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right;
buttonDown.BackgroundImage = speed_Boat.Properties.Resources.DOWN;
buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
buttonDown.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
buttonDown.Location = new System.Drawing.Point(716, 408);
buttonDown.Name = "buttonDown";
buttonDown.Size = new System.Drawing.Size(30, 30);
buttonDown.TabIndex = 8;
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += buttonMove_Click;
//
// buttonRight
//
buttonRight.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right;
buttonRight.BackgroundImage = speed_Boat.Properties.Resources.RIGHT;
buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
buttonRight.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
buttonRight.Location = new System.Drawing.Point(752, 408);
buttonRight.Name = "buttonRight";
buttonRight.Size = new System.Drawing.Size(30, 30);
buttonRight.TabIndex = 7;
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += buttonMove_Click;
//
// comboBox1
//
comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
comboBox1.FormattingEnabled = true;
comboBox1.Items.AddRange(new object[] { "MoveToCenter", "MoveToBorder" });
comboBox1.Location = new System.Drawing.Point(637, 12);
comboBox1.Name = "comboBox1";
comboBox1.Size = new System.Drawing.Size(151, 28);
comboBox1.TabIndex = 11;
//
// StepButton
//
StepButton.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left;
StepButton.BackColor = System.Drawing.Color.White;
StepButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
StepButton.Location = new System.Drawing.Point(731, 46);
StepButton.Name = "StepButton";
StepButton.Size = new System.Drawing.Size(57, 33);
StepButton.TabIndex = 12;
StepButton.Text = "Шаг";
StepButton.UseVisualStyleBackColor = false;
StepButton.Click += StepButton_Click;
//
// buttonCreateSpeedBoat
//
buttonCreateSpeedBoat.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left;
buttonCreateSpeedBoat.BackColor = System.Drawing.Color.White;
buttonCreateSpeedBoat.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
buttonCreateSpeedBoat.Location = new System.Drawing.Point(121, 387);
buttonCreateSpeedBoat.Name = "buttonCreateSpeedBoat";
buttonCreateSpeedBoat.Size = new System.Drawing.Size(143, 51);
buttonCreateSpeedBoat.TabIndex = 13;
buttonCreateSpeedBoat.Text = "Создать скоростной катер";
buttonCreateSpeedBoat.UseVisualStyleBackColor = false;
buttonCreateSpeedBoat.Click += buttonCreateSpeedBoat_Click;
//
// BoatSelectButton
//
BoatSelectButton.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left;
BoatSelectButton.BackColor = System.Drawing.Color.White;
BoatSelectButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
BoatSelectButton.Location = new System.Drawing.Point(637, 294);
BoatSelectButton.Name = "BoatSelectButton";
BoatSelectButton.Size = new System.Drawing.Size(151, 41);
BoatSelectButton.TabIndex = 18;
BoatSelectButton.Text = "Выбор катера";
BoatSelectButton.UseVisualStyleBackColor = false;
BoatSelectButton.Click += BoatSelectButton_Click;
//
// FormSpeedBoat
//
AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
ClientSize = new System.Drawing.Size(800, 450);
Controls.Add(BoatSelectButton);
Controls.Add(buttonCreateSpeedBoat);
Controls.Add(StepButton);
Controls.Add(comboBox1);
Controls.Add(buttonUp);
Controls.Add(buttonLeft);
Controls.Add(buttonDown);
Controls.Add(buttonRight);
Controls.Add(buttonCreate);
Controls.Add(pictureBoxSpeedBoat);
Name = "FormSpeedBoat";
Text = "Движение катера";
((System.ComponentModel.ISupportInitialize)pictureBoxSpeedBoat).EndInit();
ResumeLayout(false);
}
#endregion
private System.Windows.Forms.PictureBox pictureBoxSpeedBoat;
private System.Windows.Forms.Button buttonCreate;
private System.Windows.Forms.Button buttonUp;
private System.Windows.Forms.Button buttonLeft;
private System.Windows.Forms.Button buttonDown;
private System.Windows.Forms.Button buttonRight;
private System.Windows.Forms.ComboBox comboBox1;
private System.Windows.Forms.Button StepButton;
private System.Windows.Forms.Button buttonCreateSpeedBoat;
private System.Windows.Forms.ColorDialog mainColorDialog;
private System.Windows.Forms.ColorDialog additionalColorDialog;
private System.Windows.Forms.Button BoatSelectButton;
}
}

View File

@ -0,0 +1,183 @@
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 SpeedBoatLab.Drawings;
using SpeedBoatLab.Entity;
using speed_Boat.MovementStrategy;
namespace SpeedBoatLab
{
public partial class FormSpeedBoat : Form
{
Color mainColor = Color.White;
Color addColor = Color.White;
/// <summary>
/// Поле-объект для прорисовки объекта
/// </summary>
private DrawingBoat? _boatMovement;
/// <summary>
/// Стратегия перемещения
/// </summary>
private AbstractStrategy? _abstractStrategy;
/// <summary>
/// Выбранный автомобиль
/// </summary>
public DrawingBoat? SelectedBoat { get; private set; }
public FormSpeedBoat()
{
InitializeComponent();
_abstractStrategy = null;
SelectedBoat = null;
}
/// <summary>
/// Метод прорисовки лодки
/// </summary>
private void Draw()
{
if (_boatMovement == null)
{
return;
}
Bitmap bmp = new(pictureBoxSpeedBoat.Width, pictureBoxSpeedBoat.Height);
Graphics gr = Graphics.FromImage(bmp);
_boatMovement.DrawTransport(gr);
pictureBoxSpeedBoat.Image = bmp;
}
/// <summary>
/// Обработка создания обьекта
/// </summary>
private void buttonCreate_Click(object sender, EventArgs e)
{
mainColorDialog.ShowDialog();
mainColor = mainColorDialog.Color;
Random random = new();
if (mainColor == Color.White)
{
mainColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
}
_boatMovement = new DrawingBoat(random.Next(100, 300),
random.Next(1000, 3000),
mainColor,
pictureBoxSpeedBoat.Width, pictureBoxSpeedBoat.Height);
///startXCoord and startYCoord
_boatMovement.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
/// <summary>
/// Обработка создания скоростного обьекта
/// </summary>
private void buttonCreateSpeedBoat_Click(object sender, EventArgs e)
{
mainColorDialog.ShowDialog();
mainColor = mainColorDialog.Color;
additionalColorDialog.ShowDialog();
addColor = additionalColorDialog.Color;
Random random = new();
if (mainColor == Color.White || addColor == Color.White)
{
mainColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
addColor = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
}
_boatMovement = new DrawingSpeedBoat(random.Next(100, 300),
random.Next(1000, 3000),
mainColor,
addColor,
true,
Convert.ToBoolean(random.Next(0, 2)),
pictureBoxSpeedBoat.Width, pictureBoxSpeedBoat.Height);
///startXCoord and startYCoord
_boatMovement.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
/// <summary>
/// Обработка движения обьекта
/// </summary>
private void buttonMove_Click(object sender, EventArgs e)
{
if (_boatMovement == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
switch (name)
{
case "buttonUp":
_boatMovement.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
_boatMovement.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
_boatMovement.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
_boatMovement.MoveTransport(DirectionType.Right);
break;
}
Draw();
}
/// <summary>
/// Обработка нажатия кнопки "Шаг"
/// </summary>
private void StepButton_Click(object sender, EventArgs e)
{
if (_boatMovement == null)
{
return;
}
if (comboBox1.Enabled)
{
_abstractStrategy = comboBox1.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(new DrawingObjectBoat(_boatMovement), pictureBoxSpeedBoat.Width, pictureBoxSpeedBoat.Height);
comboBox1.Enabled = false;
}
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBox1.Enabled = true;
_abstractStrategy = null;
}
}
private void BoatSelectButton_Click(object sender, EventArgs e)
{
SelectedBoat = _boatMovement;
DialogResult = DialogResult.OK;
}
}
}

View File

@ -0,0 +1,126 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="mainColorDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="additionalColorDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>161, 17</value>
</metadata>
</root>

View File

@ -0,0 +1,160 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using speed_Boat.Exceptions;
namespace speed_Boat.Generics
{
internal class GenericClass<T> where T : class
{
/// <summary>
/// Массив объектов, которые храним
/// </summary>
private readonly List<T?> _places;
/// <summary>
/// Количество объектов в массиве
/// </summary>
public int Count => _places.Count;
/// <summary>
/// Максимальное количество обьектов в списке
/// </summary>
private readonly int _maxCount;
/// <summary>
/// Сортировка набора объектов
/// </summary>
/// <param name="comparer"></param>
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
/// <summary>
/// Конструктор
/// </summary>
public GenericClass(int count)
{
_maxCount = count;
_places = new List<T?>(count);
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
public int Insert(T boat, IEqualityComparer<T>? equal = null)
{
if (_places.Count == _maxCount)
throw new StorageOverflowException(_maxCount);
Insert(boat, 0, equal);
return 0;
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию.
/// Если позиция пуста, то производится вставка.
/// Если позиция занята, то происходит сдвиг элементов
/// вправо(при возможности) на одну позицию.
/// </summary>
public bool Insert(T boat, int position, IEqualityComparer<T>? equal = null)
{
if (!(position >= 0 && position <= Count))
return false;
if (equal != null)
{
if (_places.Contains(boat, equal))
{
throw new ArgumentException((nameof(boat)));
}
}
if (_places.Count == 0 && position == 0)
{
_places.Add(boat);
return true;
}
else if (_places.Count == 0 && position != 0)
return false;
if (_places[position] == null)
{
_places[position] = boat;
return true;
}
if (_places.Count < _maxCount)
{
_places.Add(boat);
for (int i = position; i < _places.Count; i++)
{
T temp = _places[i];
_places[i] = _places[_places.Count - 1];
_places[_places.Count - 1] = temp;
}
return true;
}
else
{
throw new StorageOverflowException();
}
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
public bool Remove(int position)
{
if (position < 0 || position >= Count)
{
throw new BoatNotFoundException();
}
if (_places[position] == null)
{
throw new BoatNotFoundException();
}
_places[position] = null;
return true;
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
public T? this[int position]
{
get
{
if (position < 0 || position >= Count)
{
return null;
}
else
{
return _places[position];
}
}
set
{
if (position < 0 || position >= Count)
{
MessageBox.Show("Позиция элемента находится вне списка");
}
else if(_places.Count >= Count)
{
MessageBox.Show("Вставка невозможна, т.к. список заполнен");
}
else
{
Insert(value, position);
}
}
}
///<summary>
/// Проход по списку
/// </summary>
public IEnumerable<T?> GetBoats(int? maxBoats = null)
{
for(int i = 0; i < _places.Count; i++)
{
yield return _places[i];
if (maxBoats.HasValue && i == maxBoats.Value)
{
yield break;
}
}
}
}
}

View File

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SpeedBoatLab.Drawings;
namespace speed_Boat.MovementStrategy
{
public interface IMovementObject
{
//Получение координаты Х обьекта
ObjectParameters? GetObjectPosition { get; }
//шаг обьекта
int GetStep { get; }
//проверка на перемещение
bool CheckCanMove(DirectionType direction);
//изменение направления перемещения обьекта
void MoveObject(DirectionType direction);
}
}

View File

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

View File

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

View File

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

View File

@ -0,0 +1,46 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using System;
using System.Windows.Forms;
using System.IO;
namespace SpeedBoatLab
{
static class Program
{
[STAThread]
static void Main()
{
ApplicationConfiguration.Initialize();
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormBoatCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormBoatCollection>().AddLogging(option =>
{
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();
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

View File

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

View File

@ -0,0 +1,133 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<data name="DOWN" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\resources\DOWN.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="LEFT" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\resources\LEFT.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="RIGHT" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\resources\RIGHT.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="UP" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\resources\UP.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
</root>

View File

@ -0,0 +1,246 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SpeedBoatLab;
using System.Drawing;
using SpeedBoatLab.Entity;
using speed_Boat.MovementStrategy;
namespace SpeedBoatLab.Drawings
{
public class DrawingBoat
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityBoat? _entityBoat { get; protected set; }
/// <summary>
/// Ширина окна
/// </summary>
public int screenWidth;
/// <summary>
/// Высота окна
/// </summary>
public int screenHeight;
/// <summary>
/// Х-координата обьекта
/// </summary>
protected int startXCoord;
/// <summary>
/// Y-координата обьекта
/// </summary>
protected int startYCoord;
/// <summary>
/// Ширина обьекта
/// </summary>
protected readonly int widthBoat = 100;
/// <summary>
/// Высота обьекта
/// </summary>
protected readonly int heightBoat = 80;
/// <summary>
/// Х-координата обьекта
/// </summary>
public int GetPoseX => startXCoord;
/// <summary>
/// Y-координата обьекта
/// </summary>
public int GetPoseY => startYCoord;
/// <summary>
/// Ширина обьекта
/// </summary>
public int GetWidth => widthBoat;
/// <summary>
/// Высота обьекта
/// </summary>
public int GetHeight => heightBoat;
/// <summary>
/// Получение объекта IMoveableObject из объекта DrawningBoat
/// </summary>
public IMovementObject GetMoveableObject => new DrawingObjectBoat(this);
public bool CanMove(DirectionType direction)
{
if (_entityBoat == null)
{
return false;
}
return direction switch
{
//Left
DirectionType.Left => startXCoord - _entityBoat.Step > 0,
//Up
DirectionType.Up => startYCoord - _entityBoat.Step > 0,
//Down
DirectionType.Down => startYCoord + _entityBoat.Step < screenHeight,
//Right
DirectionType.Right => startXCoord + _entityBoat.Step < screenWidth
};
}
//Изменение направления перемещения
public void MoveTransport(DirectionType direction)
{
if(!CanMove(direction) || _entityBoat == null)
{
return;
}
switch(direction)
{
case DirectionType.Left:
startXCoord -= (int)_entityBoat.Step;
break;
case DirectionType.Up:
startYCoord -= (int)_entityBoat.Step;
break;
case DirectionType.Right:
startXCoord += (int)_entityBoat.Step;
break;
case DirectionType.Down:
startYCoord += (int)_entityBoat.Step;
break;
}
}
/// <summary>
/// конструктор
/// </summary>
public DrawingBoat(int speed, double weight, Color mainColor, int width, int height)
{
screenWidth = width;
screenHeight = height;
_entityBoat = new EntityBoat(speed, weight, mainColor);
/// <summary>
/// Проверка на вместимость обьекта в рамки сцены
/// </summary>
if ((widthBoat >= screenWidth) || (heightBoat >= screenHeight))
{
Console.WriteLine("проверка не пройдена, нельзя создать объект в этих размерах");
if(widthBoat >= screenWidth)
{
widthBoat = screenWidth - widthBoat;
}
if (heightBoat >= screenWidth)
{
heightBoat = screenWidth - heightBoat;
}
}
else
Console.WriteLine("объект создан");
}
/// <summary>
/// конструктор
/// </summary>
protected DrawingBoat(int speed, double weight, Color mainColor, int width, int height, int _widthBoat, int _heightBoat)
{
screenWidth = width;
screenHeight = height;
widthBoat = _widthBoat;
heightBoat = _heightBoat;
_entityBoat = new EntityBoat(speed, weight, mainColor);
}
/// <summary>
/// Установка позиции
/// </summary>
public void SetPosition(int x, int y)
{
if ((x + widthBoat > screenWidth) || (y + heightBoat > screenHeight))
{
startXCoord = screenWidth - widthBoat;
startYCoord = screenHeight - heightBoat;
}
else
{
startXCoord = x;
startYCoord = y;
}
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
public void MoveBoat(DirectionType direction)
{
if (_entityBoat == null)
{
return;
}
switch (direction)
{
//влево
case DirectionType.Left:
if (startXCoord - _entityBoat.Step > 0)
{
startXCoord -= (int)_entityBoat.Step;
}
break;
//вверх
case DirectionType.Up:
if (startYCoord - _entityBoat.Step > 0)
{
startYCoord -= (int)_entityBoat.Step;
}
break;
// вправо
case DirectionType.Right:
if (startXCoord + _entityBoat.Step + widthBoat < screenWidth)
{
startXCoord += (int)_entityBoat.Step;
}
break;
//вниз
case DirectionType.Down:
if (startYCoord + _entityBoat.Step + heightBoat < screenHeight)
{
startYCoord += (int)_entityBoat.Step;
}
break;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
public virtual void DrawTransport(Graphics g)
{
if (_entityBoat == null)
{
return;
}
Pen pen = new(Color.Black);
Brush mainBrush = new SolidBrush(_entityBoat.MainColor);
#region Координаты переда лодки
Point b1 = new Point(startXCoord + 80, startYCoord + 20);
Point b2 = new Point(startXCoord + 100, startYCoord + 40);
Point b3 = new Point(startXCoord + 80, startYCoord + 60);
Point[] pointsBoat = { b1, b2, b3 };
#endregion
//основа катера
g.DrawRectangle(pen, startXCoord + 20, startYCoord + 20, widthBoat - 40, heightBoat - 40);
g.DrawEllipse(pen, startXCoord + 25, startYCoord + 25, widthBoat - 50, heightBoat - 50);
g.DrawPolygon(pen, pointsBoat);
g.FillRectangle(mainBrush, startXCoord + 20, startYCoord + 20, widthBoat - 40, heightBoat - 40);
g.FillEllipse(mainBrush, startXCoord + 25, startYCoord + 25, widthBoat - 50, heightBoat - 50);
g.FillPolygon(mainBrush, pointsBoat);
}
public void SetBodyColor(Color color)
{
(_entityBoat as EntityBoat).setColor(color);
}
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace speed_Boat.MovementStrategy
{
public enum Status
{
NotInit = 1,
InProgress = 2,
Finish = 3
}
}

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 speed_Boat.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 contex) : base(info, contex) { }
}
}

View File

@ -0,0 +1,20 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/log_.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "speed_Boat"
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

View File

@ -0,0 +1,36 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net7.0-windows</TargetFramework>
<UseWindowsForms>true</UseWindowsForms>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" 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="NLog.Extensions.Logging" Version="5.3.5" />
<PackageReference Include="Serilog" Version="3.1.1" />
<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>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
</Project>