Compare commits

...

8 Commits

19 changed files with 1174 additions and 249 deletions

View File

@ -0,0 +1,109 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WarmlyShip.DrawingObjects;
namespace WarmlyShip.MovementStrategy
{
public abstract class AbstractStrategy
{
private IMoveableObject? _moveableObject;
private Status _state = Status.NotInit;
protected int FieldWidth { get; private set; }
protected int FieldHeight { get; private set; }
public Status GetStatus() { return _state; }
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;
}
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,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WarmlyShip.DrawingObjects;
namespace WarmlyShip.MovementStrategy
{
public class DrawingObjectShip : IMoveableObject
{
private readonly DrawingWarmlyShip? _drawingWarmlyShip = null;
public DrawingObjectShip(DrawingWarmlyShip drawingWarmlyShip)
{
_drawingWarmlyShip = drawingWarmlyShip;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_drawingWarmlyShip == null || _drawingWarmlyShip.EntityWarmlyShip == null)
{
return null;
}
return new ObjectParameters(_drawingWarmlyShip.GetPosX,
_drawingWarmlyShip.GetPosY, _drawingWarmlyShip.GetWidth, _drawingWarmlyShip.GetHeight);
}
}
public int GetStep => (int)(_drawingWarmlyShip?.EntityWarmlyShip?.Step ?? 0);
public bool CheckCanMove(DirectionType direction) =>
_drawingWarmlyShip?.CanMove(direction) ?? false;
public void MoveObject(DirectionType direction) =>
_drawingWarmlyShip?.MoveTransport(direction);
}
}

View File

@ -3,72 +3,42 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WarmlyShip.Entities;
using WarmlyShip.MovementStrategy;
namespace WarmlyShip
namespace WarmlyShip.DrawingObjects
{
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
public class DrawingWarmlyShip
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityWarmlyShip? EntityWarmlyShip { get; private set; }
/// <summary>
/// Ширина окна
/// </summary>
public EntityWarmlyShip? EntityWarmlyShip { get; protected set; }
private int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int _pictureHeight;
/// <summary>
/// Левая координата прорисовки теплохода
/// </summary>
private int _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки теплохода
/// </summary>
private int _startPosY;
/// <summary>
/// Ширина прорисовки теплохода
/// </summary>
private readonly int _WarmlyShipWidth = 180;
/// <summary>
/// Высота прорисовки теплохода
/// </summary>
private readonly int _WarmlyShipHeight = 185;
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет корпуса</param>
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="pipes">Признак наличия труб</param>
/// <param name="section">Признак наличия отсека для топлива</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <returns>true - объект создан, false - проверка не пройдена,нельзя создать объект в этих размерах</returns>
public bool Init(int speed, double weight, Color bodyColor, Color additionalColor, bool pipes, bool section,
int width, int height)
protected int _startPosX;
protected int _startPosY;
protected readonly int _WarmlyShipWidth = 185;
protected readonly int _WarmlyShipHeight = 180;
public DrawingWarmlyShip(int speed, double weight, Color bodyColor, int width, int height)
{
if (width <_WarmlyShipWidth || height <_WarmlyShipHeight)
if (width < _WarmlyShipWidth || height < _WarmlyShipHeight)
{
return false;
return;
}
_pictureWidth = width;
_pictureHeight = height;
EntityWarmlyShip = new EntityWarmlyShip();
EntityWarmlyShip.Init(speed, weight, bodyColor, additionalColor, pipes, section);
return true;
EntityWarmlyShip = new EntityWarmlyShip(speed, weight, bodyColor);
}
protected DrawingWarmlyShip(int speed, double weight, Color bodyColor, int
width, int height, int warmlyShipWidth, int warmlyShipHeight)
{
if (width <= _WarmlyShipWidth || height <= _WarmlyShipHeight)
return;
_pictureWidth = width;
_pictureHeight = height;
_WarmlyShipWidth = warmlyShipWidth;
_WarmlyShipHeight = warmlyShipHeight;
EntityWarmlyShip = new EntityWarmlyShip(speed, weight, bodyColor);
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
if (x >= 0 && x + _WarmlyShipWidth <= _pictureWidth && y >= 0 && y + _WarmlyShipHeight <= _pictureHeight)
@ -77,53 +47,7 @@ namespace WarmlyShip
_startPosY = y;
}
}
/// <summary>
/// Изменение направления перемещения
/// </summary>
/// <param name="direction">Направление</param>
public void MoveTransport(DirectionType direction)
{
if (EntityWarmlyShip == null)
{
return;
}
switch (direction)
{
//влево
case DirectionType.Left:
if (_startPosX - EntityWarmlyShip.Step > 0)
{
_startPosX -= (int)EntityWarmlyShip.Step;
}
break;
//вверх
case DirectionType.Up:
if (_startPosY - EntityWarmlyShip.Step > 0)
{
_startPosY -= (int)EntityWarmlyShip.Step;
}
break;
// вправо
case DirectionType.Right:
if (_startPosX + _WarmlyShipWidth + EntityWarmlyShip.Step < _pictureWidth)
{
_startPosX += (int)EntityWarmlyShip.Step;
}
break;
//вниз
case DirectionType.Down:
if (_startPosY + _WarmlyShipHeight + EntityWarmlyShip.Step < _pictureHeight)
{
_startPosY += (int)EntityWarmlyShip.Step;
}
break;
}
}
/// <summary>
/// Прорисовка объекта
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
public virtual void DrawTransport(Graphics g)
{
if (EntityWarmlyShip == null)
{
@ -131,7 +55,7 @@ namespace WarmlyShip
}
Pen pen = new(Color.Black, 2);
Pen anchor = new(Color.Black, 4);
Brush additionalBrush = new SolidBrush(EntityWarmlyShip.BodyColor);
Brush bodyBrush = new SolidBrush(EntityWarmlyShip.BodyColor);
//корпус теплохода
Point[] hull = new Point[]
{
@ -140,31 +64,70 @@ namespace WarmlyShip
new Point(_startPosX + 140, _startPosY + 185),
new Point(_startPosX + 40, _startPosY + 185),
};
g.FillPolygon(additionalBrush, hull);
g.FillPolygon(bodyBrush, hull);
g.DrawPolygon(pen, hull);
Brush bra = new SolidBrush(EntityWarmlyShip.AdditionalColor);
//палуба
g.FillRectangle(bra, _startPosX + 25, _startPosY + 80, 130, 30);
g.FillRectangle(bodyBrush, _startPosX + 25, _startPosY + 80, 130, 30);
g.DrawRectangle(pen, _startPosX + 25, _startPosY + 80, 130, 30);
//отсек для топлива
Brush brGray = new SolidBrush(Color.Gray);
if (EntityWarmlyShip.Section)
{
g.FillEllipse(brGray, _startPosX + 130, _startPosY + 130, 20, 20);
g.DrawEllipse(pen, _startPosX + 130, _startPosY + 130, 20, 20);
}
//трубы
if (EntityWarmlyShip.Pipes)
{
g.FillRectangle(brGray, _startPosX + 55, _startPosY, 25, 80);
g.DrawRectangle(pen, _startPosX + 55, _startPosY, 25, 80);
g.FillRectangle(brGray, _startPosX + 90, _startPosY + 20, 25, 60);
g.DrawRectangle(pen, _startPosX + 90, _startPosY + 20, 25, 60);
}
//якорь
g.DrawLine(anchor, new Point(_startPosX + 50, _startPosY + 130), new Point(_startPosX + 50,_startPosY + 150));
g.DrawLine(anchor, new Point(_startPosX + 40, _startPosY + 140), new Point(_startPosX + 60, _startPosY + 140));
g.DrawLine(anchor, new Point(_startPosX + 45, _startPosY + 150), new Point(_startPosX + 55, _startPosY + 150));
}
public int GetPosX => _startPosX;
public int GetPosY => _startPosY;
public int GetWidth => _WarmlyShipWidth;
public int GetHeight => _WarmlyShipHeight;
public bool CanMove(DirectionType direction)
{
if (EntityWarmlyShip == null)
{
return false;
}
return direction switch
{
//влево
DirectionType.Left => _startPosX - EntityWarmlyShip.Step > 0,
//вверх
DirectionType.Up => _startPosY - EntityWarmlyShip.Step > 0,
//вправо
DirectionType.Right => _startPosX + EntityWarmlyShip.Step + _WarmlyShipWidth < _pictureWidth,
//вниз
DirectionType.Down => _startPosY + EntityWarmlyShip.Step + _WarmlyShipHeight < _pictureHeight,
_ => false,
};
}
public void MoveTransport(DirectionType direction)
{
if (!CanMove(direction) || EntityWarmlyShip == null)
{
return;
}
switch (direction)
{
//влево
case DirectionType.Left:
_startPosX -= (int)EntityWarmlyShip.Step;
break;
//вверх
case DirectionType.Up:
_startPosY -= (int)EntityWarmlyShip.Step;
break;
// вправо
case DirectionType.Right:
_startPosX += (int)EntityWarmlyShip.Step;
break;
//вниз
case DirectionType.Down:
_startPosY += (int)EntityWarmlyShip.Step;
break;
}
}
/// <summary>
/// Получение объекта IMoveableObject из объекта DrawingCar
/// </summary>
public IMoveableObject GetMoveableObject => new DrawingObjectShip(this);
}
}

View File

@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WarmlyShip.Entities;
namespace WarmlyShip.DrawingObjects
{
public class DrawingWarmlyShipWithPipes : DrawingWarmlyShip
{
public DrawingWarmlyShipWithPipes(int speed, double weight, Color bodyColor, Color
additionalColor, bool pipes, bool section, int width, int height)
: base(speed, weight, bodyColor, width, height, 185, 180)
{
if (EntityWarmlyShip != null)
{
EntityWarmlyShip = new EntityWarmlyShipWithPipes(speed, weight, bodyColor, additionalColor, pipes, section);
}
}
public override void DrawTransport(Graphics g)
{
if (EntityWarmlyShip is not EntityWarmlyShipWithPipes warmlyShip)
{
return;
}
Pen pen = new(Color.Black, 2);
Brush additionalBrush = new SolidBrush(warmlyShip.AdditionalColor);
base.DrawTransport(g);
//отсек для топлива
Brush brGray = new SolidBrush(Color.Gray);
if (warmlyShip.Section)
{
g.FillEllipse(brGray, _startPosX + 130, _startPosY + 130, 20, 20);
g.DrawEllipse(pen, _startPosX + 130, _startPosY + 130, 20, 20);
}
//трубы
if (warmlyShip.Pipes)
{
g.FillRectangle(additionalBrush, _startPosX + 55, _startPosY, 25, 80);
g.DrawRectangle(pen, _startPosX + 55, _startPosY, 25, 80);
g.FillRectangle(additionalBrush, _startPosX + 90, _startPosY + 20, 25, 60);
g.DrawRectangle(pen, _startPosX + 90, _startPosY + 20, 25, 60);
}
}
}
}

View File

@ -4,56 +4,19 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip
namespace WarmlyShip.Entities
{
public class EntityWarmlyShip
{
/// <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; }
/// <summary>
/// Признак (опция) наличия труб
/// </summary>
public bool Pipes { get; private set; }
/// <summary>
/// Признак (опция) наличия отсека для топлива
/// </summary>
public bool Section { get; private set; }
/// <summary>
/// Шаг перемещения теплохода
/// </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="pipes">Признак наличия труб</param>
/// <param name="section">Признак наличия отсека для топлива</param>
public void Init(int speed, double weight, Color bodyColor, Color
additionalColor, bool pipes, bool section)
public EntityWarmlyShip(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor;
Pipes = pipes;
Section = section;
}
}
}

View File

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip.Entities
{
public class EntityWarmlyShipWithPipes : EntityWarmlyShip
{
public Color AdditionalColor { get; private set; }
public bool Pipes { get; private set; }
public bool Section { get; private set; }
public EntityWarmlyShipWithPipes(int speed, double weight, Color bodyColor, Color
additionalColor, bool pipes, bool section)
: base (speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
Pipes = pipes;
Section = section;
}
}
}

View File

@ -0,0 +1,134 @@
namespace WarmlyShip
{
partial class FormShipCollection
{
/// <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.pictureBoxCollection = new System.Windows.Forms.PictureBox();
this.panelCollection = new System.Windows.Forms.Panel();
this.labelCollection = new System.Windows.Forms.Label();
this.buttonRefreshCollection = new System.Windows.Forms.Button();
this.buttonRemoveShip = new System.Windows.Forms.Button();
this.buttonAddShip = new System.Windows.Forms.Button();
this.maskedTextBoxNumber = new System.Windows.Forms.MaskedTextBox();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).BeginInit();
this.panelCollection.SuspendLayout();
this.SuspendLayout();
//
// pictureBoxCollection
//
this.pictureBoxCollection.Location = new System.Drawing.Point(0, 0);
this.pictureBoxCollection.Name = "pictureBoxCollection";
this.pictureBoxCollection.Size = new System.Drawing.Size(700, 453);
this.pictureBoxCollection.TabIndex = 0;
this.pictureBoxCollection.TabStop = false;
//
// panelCollection
//
this.panelCollection.Controls.Add(this.maskedTextBoxNumber);
this.panelCollection.Controls.Add(this.labelCollection);
this.panelCollection.Controls.Add(this.buttonRefreshCollection);
this.panelCollection.Controls.Add(this.buttonRemoveShip);
this.panelCollection.Controls.Add(this.buttonAddShip);
this.panelCollection.Location = new System.Drawing.Point(699, 0);
this.panelCollection.Name = "panelCollection";
this.panelCollection.Size = new System.Drawing.Size(218, 453);
this.panelCollection.TabIndex = 1;
//
// labelCollection
//
this.labelCollection.AutoSize = true;
this.labelCollection.Location = new System.Drawing.Point(3, 9);
this.labelCollection.Name = "labelCollection";
this.labelCollection.Size = new System.Drawing.Size(103, 20);
this.labelCollection.TabIndex = 2;
this.labelCollection.Text = "Инструменты";
//
// buttonRefreshCollection
//
this.buttonRefreshCollection.Location = new System.Drawing.Point(16, 239);
this.buttonRefreshCollection.Name = "buttonRefreshCollection";
this.buttonRefreshCollection.Size = new System.Drawing.Size(171, 40);
this.buttonRefreshCollection.TabIndex = 5;
this.buttonRefreshCollection.Text = "Обновить коллекцию";
this.buttonRefreshCollection.UseVisualStyleBackColor = true;
this.buttonRefreshCollection.Click += new System.EventHandler(this.ButtonRefreshCollection_Click);
//
// buttonRemoveShip
//
this.buttonRemoveShip.Location = new System.Drawing.Point(16, 166);
this.buttonRemoveShip.Name = "buttonRemoveShip";
this.buttonRemoveShip.Size = new System.Drawing.Size(171, 40);
this.buttonRemoveShip.TabIndex = 4;
this.buttonRemoveShip.Text = "Удалить теплоход";
this.buttonRemoveShip.UseVisualStyleBackColor = true;
this.buttonRemoveShip.Click += new System.EventHandler(this.ButtonRemoveShip_Click);
//
// buttonAddShip
//
this.buttonAddShip.Location = new System.Drawing.Point(16, 38);
this.buttonAddShip.Name = "buttonAddShip";
this.buttonAddShip.Size = new System.Drawing.Size(171, 40);
this.buttonAddShip.TabIndex = 2;
this.buttonAddShip.Text = "Добавить теплоход";
this.buttonAddShip.UseVisualStyleBackColor = true;
this.buttonAddShip.Click += new System.EventHandler(this.ButtonAddShip_Click);
//
// maskedTextBoxNumber
//
this.maskedTextBoxNumber.Location = new System.Drawing.Point(16, 117);
this.maskedTextBoxNumber.Name = "maskedTextBoxNumber";
this.maskedTextBoxNumber.Size = new System.Drawing.Size(171, 27);
this.maskedTextBoxNumber.TabIndex = 6;
//
// FormShipCollection
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(918, 453);
this.Controls.Add(this.panelCollection);
this.Controls.Add(this.pictureBoxCollection);
this.Name = "FormShipCollection";
this.Text = "Набор теплоходов";
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).EndInit();
this.panelCollection.ResumeLayout(false);
this.panelCollection.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private PictureBox pictureBoxCollection;
private Panel panelCollection;
private Button buttonAddShip;
private Button buttonRemoveShip;
private Button buttonRefreshCollection;
private Label labelCollection;
private MaskedTextBox maskedTextBoxNumber;
}
}

View File

@ -0,0 +1,92 @@
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 WarmlyShip.DrawingObjects;
using WarmlyShip.Generics;
using WarmlyShip.MovementStrategy;
namespace WarmlyShip
{
/// <summary>
/// Форма для работы с набором объектов класса DrawningCar
/// </summary>
public partial class FormShipCollection : Form
{
/// <summary>
/// Набор объектов
/// </summary>
private readonly ShipsGenericCollection<DrawingWarmlyShip,
DrawingObjectShip> _ships;
/// <summary>
/// Конструктор
/// </summary>
public FormShipCollection()
{
InitializeComponent();
_ships = new ShipsGenericCollection<DrawingWarmlyShip, DrawingObjectShip>
(pictureBoxCollection.Width, pictureBoxCollection.Height);
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddShip_Click(object sender, EventArgs e)
{
FormWarmlyShip form = new();
if (form.ShowDialog() == DialogResult.OK)
{
if (_ships + form.SelectedShip != -1)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = _ships.ShowShips();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
}
/// <summary>
/// Удаление объекта из набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveShip_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (_ships - pos != null)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = _ships.ShowShips();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
/// <summary>
/// Обновление рисунка по набору
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
{
pictureBoxCollection.Image = _ships.ShowShips();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -29,11 +29,15 @@
private void InitializeComponent()
{
this.pictureBoxWarmlyShip = new System.Windows.Forms.PictureBox();
this.buttonCreateWarmlyShip = new System.Windows.Forms.Button();
this.buttonCreate = new System.Windows.Forms.Button();
this.buttonLeft = new System.Windows.Forms.Button();
this.buttonUp = new System.Windows.Forms.Button();
this.buttonRight = new System.Windows.Forms.Button();
this.buttonDown = new System.Windows.Forms.Button();
this.buttonRight = new System.Windows.Forms.Button();
this.comboBoxStrategy = new System.Windows.Forms.ComboBox();
this.buttonStep = new System.Windows.Forms.Button();
this.buttonSelectShip = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxWarmlyShip)).BeginInit();
this.SuspendLayout();
//
@ -47,73 +51,120 @@
this.pictureBoxWarmlyShip.TabIndex = 0;
this.pictureBoxWarmlyShip.TabStop = false;
//
// buttonCreateWarmlyShip
//
this.buttonCreateWarmlyShip.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonCreateWarmlyShip.Location = new System.Drawing.Point(12, 389);
this.buttonCreateWarmlyShip.Name = "buttonCreateWarmlyShip";
this.buttonCreateWarmlyShip.Size = new System.Drawing.Size(163, 50);
this.buttonCreateWarmlyShip.TabIndex = 1;
this.buttonCreateWarmlyShip.Text = "Создать теплоход с трубами";
this.buttonCreateWarmlyShip.UseVisualStyleBackColor = true;
this.buttonCreateWarmlyShip.Click += new System.EventHandler(this.buttonCreateWarmlyShip_Click);
//
// buttonCreate
//
this.buttonCreate.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonCreate.Location = new System.Drawing.Point(31, 411);
this.buttonCreate.Location = new System.Drawing.Point(197, 389);
this.buttonCreate.Name = "buttonCreate";
this.buttonCreate.Size = new System.Drawing.Size(94, 30);
this.buttonCreate.TabIndex = 1;
this.buttonCreate.Text = "Создать";
this.buttonCreate.Size = new System.Drawing.Size(122, 50);
this.buttonCreate.TabIndex = 2;
this.buttonCreate.Text = "Создать теплоход";
this.buttonCreate.UseVisualStyleBackColor = true;
this.buttonCreate.Click += new System.EventHandler(this.buttonCreate_Click_1);
this.buttonCreate.Click += new System.EventHandler(this.buttonCreate_Click);
//
// buttonLeft
//
this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonLeft.BackgroundImage = global::WarmlyShip.Properties.Resources.left_arrow;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.buttonLeft.Location = new System.Drawing.Point(703, 411);
this.buttonLeft.Location = new System.Drawing.Point(720, 411);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(30, 30);
this.buttonLeft.TabIndex = 2;
this.buttonLeft.TabIndex = 3;
this.buttonLeft.UseVisualStyleBackColor = true;
this.buttonLeft.Click += new System.EventHandler(this.ButtonMove_Click);
this.buttonLeft.Click += new System.EventHandler(this.buttonMove_Click);
//
// buttonUp
//
this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonUp.BackgroundImage = global::WarmlyShip.Properties.Resources.upper_arrow;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.buttonUp.Location = new System.Drawing.Point(739, 375);
this.buttonUp.Location = new System.Drawing.Point(756, 375);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(30, 30);
this.buttonUp.TabIndex = 3;
this.buttonUp.TabIndex = 4;
this.buttonUp.UseVisualStyleBackColor = true;
this.buttonUp.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonRight
//
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::WarmlyShip.Properties.Resources.right_arrow;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.buttonRight.Location = new System.Drawing.Point(775, 411);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(30, 30);
this.buttonRight.TabIndex = 4;
this.buttonRight.UseVisualStyleBackColor = true;
this.buttonRight.Click += new System.EventHandler(this.ButtonMove_Click);
this.buttonUp.Click += new System.EventHandler(this.buttonMove_Click);
//
// buttonDown
//
this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDown.BackgroundImage = global::WarmlyShip.Properties.Resources.down_arrow;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.buttonDown.Location = new System.Drawing.Point(739, 411);
this.buttonDown.Location = new System.Drawing.Point(756, 411);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(30, 30);
this.buttonDown.TabIndex = 5;
this.buttonDown.UseVisualStyleBackColor = true;
this.buttonDown.Click += new System.EventHandler(this.ButtonMove_Click);
this.buttonDown.Click += new System.EventHandler(this.buttonMove_Click);
//
// buttonRight
//
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::WarmlyShip.Properties.Resources.right_arrow;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.buttonRight.Location = new System.Drawing.Point(792, 411);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(30, 30);
this.buttonRight.TabIndex = 6;
this.buttonRight.UseVisualStyleBackColor = true;
this.buttonRight.Click += new System.EventHandler(this.buttonMove_Click);
//
// comboBoxStrategy
//
this.comboBoxStrategy.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxStrategy.FormattingEnabled = true;
this.comboBoxStrategy.Items.AddRange(new object[] {
"К центру",
"К краю"});
this.comboBoxStrategy.Location = new System.Drawing.Point(720, 13);
this.comboBoxStrategy.Name = "comboBoxStrategy";
this.comboBoxStrategy.Size = new System.Drawing.Size(151, 28);
this.comboBoxStrategy.TabIndex = 7;
//
// buttonStep
//
this.buttonStep.Location = new System.Drawing.Point(720, 56);
this.buttonStep.Name = "buttonStep";
this.buttonStep.Size = new System.Drawing.Size(150, 29);
this.buttonStep.TabIndex = 8;
this.buttonStep.Text = "Шаг";
this.buttonStep.UseVisualStyleBackColor = true;
this.buttonStep.Click += new System.EventHandler(this.buttonStep_Click);
//
// buttonSelectShip
//
this.buttonSelectShip.Location = new System.Drawing.Point(720, 107);
this.buttonSelectShip.Name = "buttonSelectShip";
this.buttonSelectShip.Size = new System.Drawing.Size(150, 29);
this.buttonSelectShip.TabIndex = 9;
this.buttonSelectShip.Text = "Выбрать теплоход";
this.buttonSelectShip.UseVisualStyleBackColor = true;
this.buttonSelectShip.Click += new System.EventHandler(this.ButtonSelectShip_Click);
//
// FormWarmlyShip
//
this.ClientSize = new System.Drawing.Size(882, 453);
this.Controls.Add(this.buttonDown);
this.Controls.Add(this.buttonSelectShip);
this.Controls.Add(this.buttonStep);
this.Controls.Add(this.comboBoxStrategy);
this.Controls.Add(this.buttonRight);
this.Controls.Add(this.buttonDown);
this.Controls.Add(this.buttonUp);
this.Controls.Add(this.buttonLeft);
this.Controls.Add(this.buttonCreate);
this.Controls.Add(this.buttonCreateWarmlyShip);
this.Controls.Add(this.pictureBoxWarmlyShip);
this.Name = "FormWarmlyShip";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
@ -125,12 +176,15 @@
}
#endregion
private PictureBox pictureBoxWarmlyShip;
private Button buttonCreateWarmlyShip;
private Button buttonCreate;
private Button buttonLeft;
private Button buttonUp;
private Button buttonRight;
private Button buttonDown;
private Button buttonRight;
private ComboBox comboBoxStrategy;
private Button buttonStep;
private Button buttonSelectShip;
}
}

View File

@ -1,21 +1,20 @@
using WarmlyShip.DrawingObjects;
using WarmlyShip.MovementStrategy;
namespace WarmlyShip
{
public partial class FormWarmlyShip : Form
{
/// <summary>
/// Ïîëå-îáúåêò äëÿ ïðîðèñîâêè îáúåêòà
/// </summary>
private DrawingWarmlyShip? _drawingWarmlyShip;
/// <summary>
/// Èíèöèàëèçàöèÿ ôîðìû
/// </summary>
private AbstractStrategy? _strategy;
public DrawingWarmlyShip? SelectedShip { get; private set; }
public FormWarmlyShip()
{
InitializeComponent();
_strategy = null;
SelectedShip = null;
}
/// <summary>
/// Ìåòîä ïðîðèñîâêè òåïëîõîäà
/// </summary>
private void Draw()
{
if (_drawingWarmlyShip == null)
@ -28,32 +27,50 @@ namespace WarmlyShip
_drawingWarmlyShip.DrawTransport(gr);
pictureBoxWarmlyShip.Image = bmp;
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreate_Click(object sender, EventArgs e)
{
Random random = new();
_drawingWarmlyShip = new DrawingWarmlyShip();
_drawingWarmlyShip.Init(random.Next(100, 300),
Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
_drawingWarmlyShip = new DrawingWarmlyShip(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)),
color,
pictureBoxWarmlyShip.Width, pictureBoxWarmlyShip.Height);
_drawingWarmlyShip.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
private void buttonCreateWarmlyShip_Click(object sender, EventArgs e)
{
Random random = new();
Color color = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
ColorDialog dialogColor = new();
if (dialogColor.ShowDialog() == DialogResult.OK)
{
color = dialogColor.Color;
}
Color addColor = Color.FromArgb(random.Next(0, 256),
random.Next(0, 256), random.Next(0, 256));
ColorDialog dialogDopColor = new();
if (dialogDopColor.ShowDialog() == DialogResult.OK)
{
addColor = dialogDopColor.Color;
}
_drawingWarmlyShip = new DrawingWarmlyShipWithPipes(random.Next(100, 300),
random.Next(1000, 3000),
color, addColor,
Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)),
pictureBoxWarmlyShip.Width, pictureBoxWarmlyShip.Height);
_drawingWarmlyShip.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
/// <summary>
/// Èçìåíåíèå ðàçìåðîâ ôîðìû
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonMove_Click(object sender, EventArgs e)
{
if (_drawingWarmlyShip == null)
@ -79,47 +96,51 @@ namespace WarmlyShip
Draw();
}
private void buttonCreate_Click_1(object sender, EventArgs e)
{
Random random = new();
_drawingWarmlyShip = new DrawingWarmlyShip ();
_drawingWarmlyShip.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)),
Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)),
pictureBoxWarmlyShip.Width, pictureBoxWarmlyShip.Height);
_drawingWarmlyShip.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
private void ButtonMove_Click(object sender, EventArgs e)
private void buttonStep_Click(object sender, EventArgs e)
{
if (_drawingWarmlyShip == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
switch (name)
if (comboBoxStrategy.Enabled)
{
case "buttonUp":
_drawingWarmlyShip.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
_drawingWarmlyShip.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
_drawingWarmlyShip.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
_drawingWarmlyShip.MoveTransport(DirectionType.Right);
break;
_strategy = comboBoxStrategy.SelectedIndex
switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(_drawingWarmlyShip.GetMoveableObject, pictureBoxWarmlyShip.Width,
pictureBoxWarmlyShip.Height);
comboBoxStrategy.Enabled = false;
}
if (_strategy == null)
{
return;
}
_strategy.MakeStep();
Draw();
if (_strategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_strategy = null;
}
}
/// <summary>
/// Âûáîð òåïëîõîäà
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSelectShip_Click(object sender, EventArgs e)
{
SelectedShip = _drawingWarmlyShip;
DialogResult = DialogResult.OK;
}
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WarmlyShip.DrawingObjects;
namespace WarmlyShip.MovementStrategy
{
public interface IMoveableObject
{
ObjectParameters? GetObjectPosition { get; }
int GetStep { get; }
bool CheckCanMove(DirectionType direction);
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 WarmlyShip.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 WarmlyShip.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,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip.MovementStrategy
{
public class ObjectParameters
{
private readonly int _x;
private readonly int _y;
private readonly int _width;
private readonly int _height;
public int LeftBorder => _x;
public int TopBorder => _y;
public int RightBorder => _x + _width;
public int DownBorder => _y + _height;
public int ObjectMiddleHorizontal => _x + _width / 2;
public int ObjectMiddleVertical => _y + _height / 2;
public ObjectParameters(int x, int y, int width, int height)
{
_x = x;
_y = y;
_width = width;
_height = height;
}
}
}

View File

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

View File

@ -0,0 +1,98 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip.Generics
{
internal class SetGeneric<T>
where T : class
{
/// <summary>
/// Массив объектов, которые храним
/// </summary>
private readonly T?[] _places;
/// <summary>
/// Количество объектов в массиве
/// </summary>
public int Count => _places.Length;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetGeneric(int count)
{
_places = new T?[count];
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="warmlyship">Добавляемый теплоход</param>
/// <returns></returns>
public int Insert(T warmlyship)
{
return Insert(warmlyship, 0);
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="warmlyship">Добавляемый теплоход</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public int Insert(T warmlyship, int position)
{
int nullIndex = -1;
int i;
if (position < 0 || position >= Count)
return -1;
for (i = position; i < Count; i++)
{
if (_places[i] == null)
{
nullIndex = i;
break;
}
}
if (nullIndex < 0)
return -1;
for (i = nullIndex; i > position; i--)
{
_places[i] = _places[i - 1];
}
_places[position] = warmlyship;
return position;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public bool Remove(int position)
{
if (position < 0 || position >= Count)
{
return false;
}
_places[position] = null;
return true;
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T? Get(int position)
{
if (position < 0 || position >= Count)
{
return null;
}
return _places[position];
}
}
}

View File

@ -0,0 +1,150 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WarmlyShip.DrawingObjects;
using WarmlyShip.MovementStrategy;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace WarmlyShip.Generics
{
internal class ShipsGenericCollection<T, U>
where T : DrawingWarmlyShip
where U : IMoveableObject
{
/// <summary>
/// Ширина окна прорисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна прорисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Размер занимаемого объектом места (ширина)
/// </summary>
private readonly int _placeSizeWidth = 185;
/// <summary>
/// Размер занимаемого объектом места (высота)
/// </summary>
private readonly int _placeSizeHeight = 185;
/// <summary>
/// Набор объектов
/// </summary>
private readonly SetGeneric<T> _collection;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
public ShipsGenericCollection(int picWidth, int picHeight)
{
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = new SetGeneric<T>(width * height);
}
/// <summary>
/// Перегрузка оператора сложения
/// </summary>
/// <param name="collect"></param>
/// <param name="obj"></param>
/// <returns></returns>
public static int operator +(ShipsGenericCollection<T, U> collect, T?
obj)
{
if (obj == null)
{
return -1;
}
return collect._collection.Insert(obj);
}
/// <summary>
/// Перегрузка оператора вычитания
/// </summary>
/// <param name="collect"></param>
/// <param name="pos"></param>
/// <returns></returns>
public static bool operator -(ShipsGenericCollection<T, U> collect, int
pos)
{
T? obj = collect._collection.Get(pos);
if (obj != null)
{
collect._collection.Remove(pos);
}
return false;
}
/// <summary>
/// Получение объекта IMoveableObject
/// </summary>
/// <param name="pos"></param>
/// <returns></returns>
public U? GetU(int pos)
{
return (U?)_collection.Get(pos)?.GetMoveableObject;
}
/// <summary>
/// Вывод всего набора объектов
/// </summary>
/// <returns></returns>
public Bitmap ShowShips()
{
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)
{
T? ship;
int width = _pictureWidth / _placeSizeWidth;
int diff = 1;
int currWidth = 0;
for (int i = 0; i < _collection.Count; i++)
{
currWidth++;
if (currWidth > width)
{
diff++;
currWidth = 1;
}
ship = _collection.Get(i);
if (ship != null)
{
ship.SetPosition((width - 1 - (i % width)) * _placeSizeWidth, i / width * _placeSizeHeight);
ship.DrawTransport(g);
}
}
}
}
}

View File

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