Готовая полностью Lab_2

This commit is contained in:
Максим Егоров 2023-12-25 02:25:54 +04:00
parent d1ed841a1f
commit ac9e6959f3
16 changed files with 718 additions and 355 deletions

View File

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

View File

@ -0,0 +1,145 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sailboat.Entities;
namespace Sailboat.DrawingObjects
{
public class DrawingBoat
{
public EntityBoat? EntityBoat { get; protected set; }
private int _pictureWidth;
private int _pictureHeight;
protected int _startPosX;
protected int _startPosY;
private readonly int _boatWidth = 160;
private readonly int _boatHeight = 160;
public int GetPosX => _startPosX;
public int GetPosY => _startPosY;
public int GetWidth => _boatWidth;
public int GetHeight => _boatHeight;
public DrawingBoat(int speed, double weight, Color bodyColor, int width, int height)
{
if (width < _boatWidth || height < _boatHeight)
{
return;
}
_pictureWidth = width;
_pictureHeight = height;
EntityBoat = new EntityBoat(speed, weight, bodyColor);
}
protected DrawingBoat(int speed, double weight, Color bodyColor, int width, int height, int boatWidth, int boatHeight)
{
if (width < _boatWidth || height < _boatHeight)
{
return;
}
_pictureWidth = width;
_pictureHeight = height;
_boatWidth = boatWidth;
_boatHeight = boatHeight;
EntityBoat = new EntityBoat(speed, weight, bodyColor);
}
public void SetPosition(int x, int y)
{
if (x < 0 || x + _boatWidth > _pictureWidth)
{
x = 0;
}
if (y < 0 || y + _boatHeight > _pictureHeight)
{
y = 0;
}
_startPosX = x;
_startPosY = y;
}
public bool CanMove(DirectionType direction)
{
if (EntityBoat == null)
{
return false;
}
return direction switch
{
//влево
DirectionType.Left => _startPosX - EntityBoat.Step > 0,
//вверх
DirectionType.Up => _startPosY - EntityBoat.Step > 0,
// вправо
DirectionType.Right => _startPosX + EntityBoat.Step < _pictureWidth,
//вниз
DirectionType.Down => _startPosY + EntityBoat.Step < _pictureHeight,
};
}
public void MoveTransport(DirectionType direction)
{
if (EntityBoat == null)
{
return;
}
switch (direction)
{
case DirectionType.Left:
if (_startPosX - EntityBoat.Step > 0)
{
_startPosX -= (int)EntityBoat.Step;
}
break;
case DirectionType.Up:
if ((_startPosY - 15) - EntityBoat.Step > 0)
{
_startPosY -= (int)EntityBoat.Step;
}
break;
case DirectionType.Right:
if (_startPosX + EntityBoat.Step + _boatWidth < _pictureWidth)
{
_startPosX += (int)EntityBoat.Step;
}
break;
case DirectionType.Down:
if (_startPosY + EntityBoat.Step + _boatHeight < _pictureHeight)
{
_startPosY += (int)EntityBoat.Step;
}
break;
}
}
public virtual void DrawTransport(Graphics g)
{
if (EntityBoat == null)
{
return;
}
Pen pen = new(Color.Black);
//Основной корпус лодки
Brush Brush = new
SolidBrush(EntityBoat.BodyColor);
Point[] hull = new Point[]
{
new Point(_startPosX + 10, _startPosY + 90),
new Point(_startPosX + 110, _startPosY + 90),
new Point(_startPosX + 140, _startPosY + 120),
new Point(_startPosX + 110, _startPosY + 150),
new Point(_startPosX + 10, _startPosY + 150)
};
g.FillPolygon(Brush, hull);
g.DrawPolygon(pen, hull);
Brush addBrush = new
SolidBrush(Color.Aqua);
//Каюта лодки
g.FillEllipse(addBrush, _startPosX + 20, _startPosY + 100, 90, 40);
g.DrawEllipse(pen, _startPosX + 20, _startPosY + 100, 90, 40);
}
}
}

View File

@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sailboat.DrawingObjects;
namespace Sailboat.MovementStrategy
{
public class DrawingObjectBoat : IMoveableObject
{
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.GetPosX, _drawingBoat.GetPosY, _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?.MoveTransport(direction);
}
}

View File

@ -2,92 +2,36 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Drawing; using System.Drawing;
using System.Linq; using System.Linq;
using System.Reflection;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Sailboat using Sailboat.Entities;
{
public class DrawingSailboat
{
public EntitySailboat? EntitySailboat { get; private set; }
private int _pictureWidth;
private int _pictureHeight;
private int _startPosX;
private int _startPosY;
private readonly int _boatWidth = 160;
private readonly int _boatHeight = 160;
public bool Init(int speed, double weight, Color bodyColor, Color additionalColor, bool hull, bool sail, int width, int height)
{
if (width < _boatWidth || height < _boatHeight)
{
return false;
}
_pictureWidth = width;
_pictureHeight = height;
EntitySailboat = new EntitySailboat();
EntitySailboat.Init(speed, weight, bodyColor, additionalColor, hull, sail);
return true;
}
public void SetPosition(int x, int y)
{
if (x < 0 || x + _boatWidth > _pictureWidth)
{
x = 0;
}
if (y < 0 || y + _boatHeight > _pictureHeight)
{
y = 0;
}
_startPosX = x;
_startPosY = y;
}
public void MoveTransport(DirectionType direction)
{
if (EntitySailboat == null)
{
return;
}
switch (direction)
{
case DirectionType.Left:
if (_startPosX - EntitySailboat.Step > 0)
{
_startPosX -= (int)EntitySailboat.Step;
}
break;
case DirectionType.Up:
if ((_startPosY - 15) - EntitySailboat.Step > 0)
{
_startPosY-= (int)EntitySailboat.Step;
}
break;
case DirectionType.Right:
if (_startPosX + EntitySailboat.Step + _boatWidth < _pictureWidth)
{
_startPosX += (int)EntitySailboat.Step;
}
break;
case DirectionType.Down:
if (_startPosY + EntitySailboat.Step + _boatHeight < _pictureHeight)
{
_startPosY += (int)EntitySailboat.Step;
}
break;
}
}
public void DrawTransport(Graphics g)
{
if (EntitySailboat == null)
{
return;
}
Pen pen = new(Color.Black, 4);
Brush additionalBrush = new
SolidBrush(EntitySailboat.AdditionalColor);
//Усиленный корпус парусной лодки namespace Sailboat.DrawingObjects
if (EntitySailboat.Hull) {
public class DrawingSailboat : DrawingBoat
{
public DrawingSailboat(int speed, double weight, Color bodyColor, Color additionalColor, bool hull, bool sail, int width, int height) :
base(speed, weight, bodyColor, width, height, 160, 160)
{
if (EntityBoat != null)
{
EntityBoat = new EntitySailboat(speed, weight, bodyColor,
additionalColor, hull, sail);
}
}
public override void DrawTransport(Graphics g)
{
if (EntityBoat is not EntitySailboat sailboat)
{
return;
}
Pen pen = new(Color.Black);
Brush additionalBrush = new
SolidBrush(sailboat.AdditionalColor);
//усиленный корпус парусной лодки
if (sailboat.Hull)
{ {
Point[] hullCooler = new Point[] Point[] hullCooler = new Point[]
{ {
@ -100,34 +44,13 @@ namespace Sailboat
g.FillPolygon(additionalBrush, hullCooler); g.FillPolygon(additionalBrush, hullCooler);
g.DrawPolygon(pen, hullCooler); g.DrawPolygon(pen, hullCooler);
} }
base.DrawTransport(g);
//Основной корпус парусной лодки
Brush Brush = new
SolidBrush(EntitySailboat.BodyColor);
Point[] hull = new Point[]
{
new Point(_startPosX + 10, _startPosY + 90),
new Point(_startPosX + 110, _startPosY + 90),
new Point(_startPosX + 140, _startPosY + 120),
new Point(_startPosX + 110, _startPosY + 150),
new Point(_startPosX + 10, _startPosY + 150)
};
g.FillPolygon(Brush, hull);
g.DrawPolygon(pen, hull);
Brush addBrush = new
SolidBrush(Color.Aqua);
//Каюта парусной лодки
g.FillEllipse(addBrush, _startPosX + 20, _startPosY + 100, 90, 40);
g.DrawEllipse(pen, _startPosX + 20, _startPosY + 100, 90, 40);
//Парус с флагом //Парус с флагом
if (EntitySailboat.Sail) if (sailboat.Sail)
{ {
Brush sailBrush = new Brush sailBrush = new
SolidBrush(EntitySailboat.AdditionalColor); SolidBrush(sailboat.AdditionalColor);
Point[] sail = new Point[] Point[] sail = new Point[]
{ {
@ -138,11 +61,12 @@ namespace Sailboat
g.FillPolygon(sailBrush, sail); g.FillPolygon(sailBrush, sail);
g.DrawPolygon(pen, sail); g.DrawPolygon(pen, sail);
//Флаг //Флаг
Brush addBrush = new
SolidBrush(Color.Aqua);
Brush flagBrush = new Brush flagBrush = new
SolidBrush(EntitySailboat.AdditionalColor); SolidBrush(sailboat.AdditionalColor);
Point[] flag = new Point[] Point[] flag = new Point[]
{ {
//new Point(_startPosX + 65, _startPosY + 125),
new Point(_startPosX + 65, _startPosY - 15), new Point(_startPosX + 65, _startPosY - 15),
new Point(_startPosX + 65, _startPosY + 10), new Point(_startPosX + 65, _startPosY + 10),
new Point(_startPosX + 20, _startPosY + 10), new Point(_startPosX + 20, _startPosY + 10),
@ -151,9 +75,7 @@ namespace Sailboat
g.FillPolygon(addBrush, flag); g.FillPolygon(addBrush, flag);
g.DrawPolygon(pen, flag); g.DrawPolygon(pen, flag);
g.DrawLine(pen, new Point(_startPosX + 65, _startPosY + 130), new Point(_startPosX + 65, _startPosY - 15)); g.DrawLine(pen, new Point(_startPosX + 65, _startPosY + 130), new Point(_startPosX + 65, _startPosY - 15));
} }
} }
} }
} }

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sailboat.Entities
{
public class EntityBoat
{
public int Speed { get; private set; }
public double Weight { get; private set; }
public Color BodyColor { get; private set; }
public double Step => (double)Speed * 100 / Weight;
public EntityBoat(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}
}

View File

@ -4,53 +4,16 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Sailboat namespace Sailboat.Entities
{ {
public class EntitySailboat public class EntitySailboat : EntityBoat
{ {
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; }
/// <summary>
/// Дополнительный цвет (для опциональных элементов)
/// </summary>
public Color AdditionalColor { get; private set; } public Color AdditionalColor { get; private set; }
/// <summary>
/// Признак (опция) наличия усиленного корпуса
/// </summary>
public bool Hull { get; private set; } public bool Hull { get; private set; }
/// <summary>
/// Признак (опция) наличия паруса с флагом
/// </summary>
public bool Sail { get; private set; } public bool Sail { get; private set; }
/// <summary> public EntitySailboat(int speed, double weight, Color bodyColor, Color
/// Шаг перемещения парусной лодки additionalColor, bool hull, bool sail) : base (speed, weight, bodyColor)
/// </summary>
public double Step => (double)Speed * 100 / Weight;
/// <summary>
/// Инициализация полей объекта-класса парусной лодки
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес парусной лодки</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="hull">Признак наличия усиленного корпуса</param>
/// <param name="sail">Признак наличия паруса с флагом</param>
public void Init(int speed, double weight, Color bodyColor, Color
additionalColor, bool hull, bool sail)
{ {
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor; AdditionalColor = additionalColor;
Hull = hull; Hull = hull;
Sail = sail; Sail = sail;

View File

@ -1,39 +0,0 @@
namespace Sailboat
{
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,10 +0,0 @@
namespace Sailboat
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}

View File

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

View File

@ -30,11 +30,14 @@
{ {
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormSailboat)); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormSailboat));
pictureBoxSailboat = new PictureBox(); pictureBoxSailboat = new PictureBox();
buttonCreate = new Button(); buttonCreateBoat = new Button();
buttonLeft = new Button(); buttonLeft = new Button();
buttonUp = new Button(); buttonUp = new Button();
buttonRight = new Button(); buttonRight = new Button();
buttonDown = new Button(); buttonDown = new Button();
buttonCreateSailboat = new Button();
comboBoxStrategy = new ComboBox();
buttonStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxSailboat).BeginInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxSailboat).BeginInit();
SuspendLayout(); SuspendLayout();
// //
@ -44,28 +47,29 @@
pictureBoxSailboat.Location = new Point(0, 0); pictureBoxSailboat.Location = new Point(0, 0);
pictureBoxSailboat.Margin = new Padding(3, 2, 3, 2); pictureBoxSailboat.Margin = new Padding(3, 2, 3, 2);
pictureBoxSailboat.Name = "pictureBoxSailboat"; pictureBoxSailboat.Name = "pictureBoxSailboat";
pictureBoxSailboat.Size = new Size(884, 461); pictureBoxSailboat.Size = new Size(834, 461);
pictureBoxSailboat.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBoxSailboat.TabIndex = 0; pictureBoxSailboat.TabIndex = 0;
pictureBoxSailboat.TabStop = false; pictureBoxSailboat.TabStop = false;
// //
// buttonCreate // buttonCreateBoat
// //
buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; buttonCreateBoat.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreate.Location = new Point(10, 417); buttonCreateBoat.Location = new Point(12, 408);
buttonCreate.Margin = new Padding(3, 2, 3, 2); buttonCreateBoat.Margin = new Padding(3, 2, 3, 2);
buttonCreate.Name = "buttonCreate"; buttonCreateBoat.Name = "buttonCreateBoat";
buttonCreate.Size = new Size(111, 30); buttonCreateBoat.Size = new Size(111, 42);
buttonCreate.TabIndex = 1; buttonCreateBoat.TabIndex = 1;
buttonCreate.Text = "Создать"; buttonCreateBoat.Text = "Создать лодку";
buttonCreate.UseVisualStyleBackColor = true; buttonCreateBoat.UseVisualStyleBackColor = true;
buttonCreate.Click += buttonCreate_Click; buttonCreateBoat.Click += buttonCreateBoat_Click;
// //
// buttonLeft // buttonLeft
// //
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = (Image)resources.GetObject("buttonLeft.BackgroundImage"); buttonLeft.BackgroundImage = (Image)resources.GetObject("buttonLeft.BackgroundImage");
buttonLeft.BackgroundImageLayout = ImageLayout.Zoom; buttonLeft.BackgroundImageLayout = ImageLayout.Zoom;
buttonLeft.Location = new Point(740, 423); buttonLeft.Location = new Point(673, 420);
buttonLeft.Margin = new Padding(3, 2, 3, 2); buttonLeft.Margin = new Padding(3, 2, 3, 2);
buttonLeft.Name = "buttonLeft"; buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(30, 30); buttonLeft.Size = new Size(30, 30);
@ -78,7 +82,7 @@
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = (Image)resources.GetObject("buttonUp.BackgroundImage"); buttonUp.BackgroundImage = (Image)resources.GetObject("buttonUp.BackgroundImage");
buttonUp.BackgroundImageLayout = ImageLayout.Zoom; buttonUp.BackgroundImageLayout = ImageLayout.Zoom;
buttonUp.Location = new Point(776, 389); buttonUp.Location = new Point(716, 386);
buttonUp.Margin = new Padding(3, 2, 3, 2); buttonUp.Margin = new Padding(3, 2, 3, 2);
buttonUp.Name = "buttonUp"; buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(30, 30); buttonUp.Size = new Size(30, 30);
@ -91,7 +95,7 @@
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = (Image)resources.GetObject("buttonRight.BackgroundImage"); buttonRight.BackgroundImage = (Image)resources.GetObject("buttonRight.BackgroundImage");
buttonRight.BackgroundImageLayout = ImageLayout.Zoom; buttonRight.BackgroundImageLayout = ImageLayout.Zoom;
buttonRight.Location = new Point(812, 423); buttonRight.Location = new Point(760, 420);
buttonRight.Margin = new Padding(3, 2, 3, 2); buttonRight.Margin = new Padding(3, 2, 3, 2);
buttonRight.Name = "buttonRight"; buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(30, 30); buttonRight.Size = new Size(30, 30);
@ -104,7 +108,7 @@
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = (Image)resources.GetObject("buttonDown.BackgroundImage"); buttonDown.BackgroundImage = (Image)resources.GetObject("buttonDown.BackgroundImage");
buttonDown.BackgroundImageLayout = ImageLayout.Zoom; buttonDown.BackgroundImageLayout = ImageLayout.Zoom;
buttonDown.Location = new Point(776, 423); buttonDown.Location = new Point(716, 420);
buttonDown.Margin = new Padding(3, 2, 3, 2); buttonDown.Margin = new Padding(3, 2, 3, 2);
buttonDown.Name = "buttonDown"; buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(30, 30); buttonDown.Size = new Size(30, 30);
@ -112,33 +116,76 @@
buttonDown.UseVisualStyleBackColor = true; buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += buttonMove_Click; buttonDown.Click += buttonMove_Click;
// //
// buttonCreateSailboat
//
buttonCreateSailboat.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateSailboat.Location = new Point(145, 408);
buttonCreateSailboat.Margin = new Padding(3, 2, 3, 2);
buttonCreateSailboat.Name = "buttonCreateSailboat";
buttonCreateSailboat.Size = new Size(111, 42);
buttonCreateSailboat.TabIndex = 6;
buttonCreateSailboat.Text = "Создать парусник";
buttonCreateSailboat.UseVisualStyleBackColor = true;
buttonCreateSailboat.Click += buttonCreateSailboat_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right;
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "До центра", "До края" });
comboBoxStrategy.Location = new Point(701, 0);
comboBoxStrategy.Margin = new Padding(3, 2, 3, 2);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(133, 23);
comboBoxStrategy.TabIndex = 7;
//
// buttonStep
//
buttonStep.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonStep.Location = new Point(701, 27);
buttonStep.Margin = new Padding(3, 2, 3, 2);
buttonStep.Name = "buttonStep";
buttonStep.Size = new Size(133, 23);
buttonStep.TabIndex = 8;
buttonStep.Text = "Шаг";
buttonStep.UseVisualStyleBackColor = true;
buttonStep.Click += buttonStep_Click;
//
// FormSailboat // FormSailboat
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(884, 461); ClientSize = new Size(834, 461);
Controls.Add(buttonStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateSailboat);
Controls.Add(buttonDown); Controls.Add(buttonDown);
Controls.Add(buttonRight); Controls.Add(buttonRight);
Controls.Add(buttonUp); Controls.Add(buttonUp);
Controls.Add(buttonLeft); Controls.Add(buttonLeft);
Controls.Add(buttonCreate); Controls.Add(buttonCreateBoat);
Controls.Add(pictureBoxSailboat); Controls.Add(pictureBoxSailboat);
Margin = new Padding(3, 2, 3, 2); Margin = new Padding(3, 2, 3, 2);
Name = "FormSailboat"; Name = "FormSailboat";
StartPosition = FormStartPosition.CenterParent; StartPosition = FormStartPosition.CenterScreen;
Text = "Sailboat"; Text = "Парусник";
Load += FormSailboat_Load; Load += FormSailboat_Load;
((System.ComponentModel.ISupportInitialize)pictureBoxSailboat).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxSailboat).EndInit();
ResumeLayout(false); ResumeLayout(false);
PerformLayout();
} }
#endregion #endregion
private PictureBox pictureBoxSailboat; private PictureBox pictureBoxSailboat;
private Button buttonCreate; private Button buttonCreateBoat;
private Button buttonLeft; private Button buttonLeft;
private Button buttonUp; private Button buttonUp;
private Button buttonRight; private Button buttonRight;
private Button buttonDown; private Button buttonDown;
private Button buttonCreateSailboat;
private ComboBox comboBoxStrategy;
private Button buttonStep;
} }
} }

View File

@ -1,37 +1,49 @@
using Sailboat.Entities;
using Sailboat.DrawingObjects;
using Sailboat.MovementStrategy;
namespace Sailboat namespace Sailboat
{ {
public partial class FormSailboat : Form public partial class FormSailboat : Form
{ {
private DrawingSailboat? _drawingSailboat; private DrawingBoat? _drawingBoat;
private AbstractStrategy? _abstractStrategy;
public FormSailboat() public FormSailboat()
{ {
InitializeComponent(); InitializeComponent();
} }
private void Draw() private void Draw()
{ {
if (_drawingSailboat == null) if (_drawingBoat == null)
{ {
return; return;
} }
Bitmap bmp = new(pictureBoxSailboat.Width, Bitmap bmp = new(pictureBoxSailboat.Width,
pictureBoxSailboat.Height); pictureBoxSailboat.Height);
Graphics gr = Graphics.FromImage(bmp); Graphics gr = Graphics.FromImage(bmp);
_drawingSailboat.DrawTransport(gr); _drawingBoat.DrawTransport(gr);
pictureBoxSailboat.Image = bmp; pictureBoxSailboat.Image = bmp;
} }
private void buttonCreate_Click(object sender, EventArgs e) private void buttonCreateBoat_Click(object sender, EventArgs e)
{ {
Random random = new(); Random random = new();
_drawingSailboat = new DrawingSailboat(); _drawingBoat = new DrawingBoat(random.Next(100, 300), random.Next(1000, 3000), Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), pictureBoxSailboat.Width, pictureBoxSailboat.Height);
_drawingSailboat.Init(random.Next(100, 300), random.Next(1000, 3000), Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), _drawingBoat.SetPosition(random.Next(10, 100), random.Next(10,
100));
Draw();
}
private void buttonCreateSailboat_Click(object sender, EventArgs e)
{
Random random = new();
_drawingBoat = new DrawingSailboat(random.Next(100, 300), random.Next(1000, 3000), Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)),
Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)), pictureBoxSailboat.Width, pictureBoxSailboat.Height); Convert.ToBoolean(random.Next(0, 2)), pictureBoxSailboat.Width, pictureBoxSailboat.Height);
_drawingSailboat.SetPosition(random.Next(10, 100), random.Next(10, 100)); _drawingBoat.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw(); Draw();
} }
private void buttonMove_Click(object sender, EventArgs e) private void buttonMove_Click(object sender, EventArgs e)
{ {
if (_drawingSailboat == null) if (_drawingBoat == null)
{ {
return; return;
} }
@ -39,20 +51,54 @@ namespace Sailboat
switch (name) switch (name)
{ {
case "buttonUp": case "buttonUp":
_drawingSailboat.MoveTransport(DirectionType.Up); _drawingBoat.MoveTransport(DirectionType.Up);
break; break;
case "buttonDown": case "buttonDown":
_drawingSailboat.MoveTransport(DirectionType.Down); _drawingBoat.MoveTransport(DirectionType.Down);
break; break;
case "buttonLeft": case "buttonLeft":
_drawingSailboat.MoveTransport(DirectionType.Left); _drawingBoat.MoveTransport(DirectionType.Left);
break; break;
case "buttonRight": case "buttonRight":
_drawingSailboat.MoveTransport(DirectionType.Right); _drawingBoat.MoveTransport(DirectionType.Right);
break; break;
} }
Draw(); Draw();
}
private void buttonStep_Click(object sender, EventArgs e)
{
if (_drawingBoat == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_abstractStrategy = comboBoxStrategy.SelectedIndex
switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(new DrawingObjectBoat(_drawingBoat), pictureBoxSailboat.Width,
pictureBoxSailboat.Height);
comboBoxStrategy.Enabled = false;
}
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_abstractStrategy = null;
}
} }
private void FormSailboat_Load(object sender, EventArgs e) private void FormSailboat_Load(object sender, EventArgs e)

View File

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

View File

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

View File

@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sailboat.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,54 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sailboat.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>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
/// <param name="width">Ширина</param>
/// <param name="height">Высота</param>
public ObjectParameters(int x, int y, int width, int height)
{
_x = x;
_y = y;
_width = width;
_height = height;
}
}
}

View File

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