Лёвушкина Анна, ПИбд-21, лаб2 простая #2

Closed
AnnaLioness wants to merge 7 commits from лаб2 into containerShip_base
17 changed files with 873 additions and 276 deletions

View File

@ -0,0 +1,139 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Lab1ContainersShip.DrawingObjects;
namespace Lab1ContainersShip.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(Direction.Left);
/// <summary>
/// Перемещение вправо
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться,
//false - неудача)</returns>
protected bool MoveRight() => MoveTo(Direction.Right);
/// <summary>
/// Перемещение вверх
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться,
//false - неудача)</returns>
protected bool MoveUp() => MoveTo(Direction.Up);
/// <summary>
/// Перемещение вниз
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться,
//false - неудача)</returns>
protected bool MoveDown() => MoveTo(Direction.Down);
/// <summary>
/// Параметры объекта
/// </summary>
protected ObjectParameters GetObjectParameters =>
_moveableObject?.GetObjectPosition;
/// <summary>
/// Шаг объекта
/// </summary>
/// <returns></returns>
protected int? GetStep()
{
if (_state != Status.InProgress)
{
return null;
}
return _moveableObject?.GetStep;
}
/// <summary>
/// Перемещение к цели
/// </summary>
protected abstract void MoveToTarget();
/// <summary>
/// Достигнута ли цель
/// </summary>
/// <returns></returns>
protected abstract bool IsTargetDestinaion();
/// <summary>
/// Попытка перемещения в требуемом направлении
/// </summary>
/// <param name="directionType">Направление</param>
/// <returns>Результат попытки (true - удалось переместиться, false -
//неудача)</returns>
private bool MoveTo(Direction direction)
{
if (_state != Status.InProgress)
{
return false;
}
if (_moveableObject?.CheckCanMove(direction) ?? false)
{
_moveableObject.MoveObject(direction);
return true;
}
return false;
}
}
}

View File

@ -2,151 +2,38 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Drawing; using System.Drawing;
using System.Linq; using System.Linq;
using System.Net.NetworkInformation;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Lab1ContainersShip.Entities;
namespace Lab1ContainersShip namespace Lab1ContainersShip.DrawingObjects
{ {
public class DrawingContainerShip internal class DrawingContainerShip : DrawingShip
{ {
/// <summary> public DrawingContainerShip(int speed, double weight, Color bodyColor, Color
/// Класс-сущность additionalColor, bool crane, bool containers, int width, int height) :
/// </summary> base(speed, weight, bodyColor,width, height, 110, 65) {
public EntityContainerShip EntityContainerShip { get; private set; } if (EntityShip != null)
/// <summary>
/// Ширина окна
/// </summary>
private int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int _pictureHeight;
/// <summary>
/// Левая координата прорисовки автомобиля
/// </summary>
private int _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки автомобиля
/// </summary>
private int _startPosY;
/// <summary>
/// Ширина прорисовки автомобиля
/// </summary>
private readonly int _shipWidth = 110;
/// <summary>
/// Высота прорисовки автомобиля
/// </summary>
private readonly int _shipHeight = 65;
public bool Init(int speed, double weight, Color bodyColor, Color
additionalColor, bool crane, bool container, int width, int height)
{
// TODO: Продумать проверки
_pictureWidth = width;
_pictureHeight = height;
if (_pictureWidth < _shipWidth || _pictureHeight < _shipHeight)
{ {
return false; EntityShip = new EntityContainerShip(speed, weight, bodyColor,
additionalColor, crane, containers);
} }
EntityContainerShip = new EntityContainerShip();
EntityContainerShip.Init(speed, weight, bodyColor, additionalColor,
crane, container);
return true;
} }
/*public bool Init(EntityContainerShip entcon, int wid, int hei) public override void DrawShip(Graphics g)
{ {
_pictureWidth = wid;
_pictureHeight = hei;
if (_pictureWidth < _shipWidth || _pictureHeight < _shipHeight)
{
return false;
}
EntityContainerShip = entcon;
return true;
}*/ if(EntityShip == null)
public void SetPosition(int x, int y)
{
// TODO: Изменение x, y
_startPosX = Math.Min(x, _pictureWidth - _shipWidth);
_startPosY = Math.Min(y, _pictureHeight - _shipHeight);
}
public void MoveTransport(Direction direction)
{
if (EntityContainerShip == null)
{ {
return; return;
} }
switch (direction) if(!(EntityShip is EntityContainerShip)) {
{
//влево
case Direction.Left:
if (_startPosX - EntityContainerShip.Step > 0)
{
_startPosX -= (int)EntityContainerShip.Step;
}
break;
//вверх
case Direction.Up:
if (_startPosY - EntityContainerShip.Step > 0)
{
_startPosY -= (int)EntityContainerShip.Step;
}
break;
// вправо
case Direction.Right:
// TODO: Продумать логику
if (_startPosX + EntityContainerShip.Step + _shipWidth < _pictureWidth)
{
_startPosX += (int)EntityContainerShip.Step;
}
break;
//вниз
case Direction.Down:
// TODO: Продумать логику
if (_startPosY + EntityContainerShip.Step + _shipHeight< _pictureHeight)
{
_startPosY += (int)EntityContainerShip.Step;
}
break;
}
}
public void DrawShip(Graphics g)
{
if (EntityContainerShip == null)
{
return; return;
} }
Pen pen = new Pen(Color.Black); Pen pen = new Pen(Color.Black);
Brush adbrush = new SolidBrush(EntityContainerShip.AdditionalColor); Brush adbrush = new SolidBrush((EntityShip as EntityContainerShip).AdditionalColor);
Brush brBlue = new SolidBrush(Color.Blue); base.DrawShip(g);
// заполнение борта if ((EntityShip as EntityContainerShip).Conteiners)
g.FillPolygon(brBlue, new PointF[]
{
new PointF(_startPosX, _startPosY+45),
new PointF(_startPosX+20, _startPosY+65),
new PointF(_startPosX+90, _startPosY+65),
new PointF(_startPosX+110, _startPosY+45),
new PointF(_startPosX, _startPosY+45)
});
//борт корабля контур
g.DrawLines(pen, new Point[] {
new Point(_startPosX, _startPosY+45),
new Point(_startPosX+20, _startPosY+65),
new Point(_startPosX+90, _startPosY+65),
new Point(_startPosX+110, _startPosY+45),
new Point(_startPosX, _startPosY+45)});
//рисунок на борту
g.DrawLine(pen, _startPosX + 23, _startPosY + 60, _startPosX + 27, _startPosY + 60);
g.DrawLine(pen, _startPosX + 25, _startPosY + 50, _startPosX + 25, _startPosY + 60);
g.DrawLine(pen, _startPosX + 20, _startPosY + 55, _startPosX + 30, _startPosY + 55);
//контейнеры
if (EntityContainerShip.Conteiners)
{ {
g.FillRectangle(adbrush, _startPosX + 30, _startPosY + 35, 35, 10); g.FillRectangle(adbrush, _startPosX + 30, _startPosY + 35, 35, 10);
g.FillRectangle(adbrush, _startPosX + 65, _startPosY + 35, 20, 10); g.FillRectangle(adbrush, _startPosX + 65, _startPosY + 35, 20, 10);
@ -163,7 +50,7 @@ additionalColor, bool crane, bool container, int width, int height)
g.DrawRectangle(pen, _startPosX + 45, _startPosY + 30, 40, 5); g.DrawRectangle(pen, _startPosX + 45, _startPosY + 30, 40, 5);
} }
//кран //кран
if (EntityContainerShip.Crane) if ((EntityShip as EntityContainerShip).Crane)
{ {
g.FillRectangle(adbrush, _startPosX + 23, _startPosY, 5, 45); g.FillRectangle(adbrush, _startPosX + 23, _startPosY, 5, 45);
g.FillRectangle(adbrush, _startPosX + 27, _startPosY + 10, 20, 3); g.FillRectangle(adbrush, _startPosX + 27, _startPosY + 10, 20, 3);

View File

@ -0,0 +1,180 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Lab1ContainersShip.Entities;
namespace Lab1ContainersShip.DrawingObjects
{
public class DrawingShip
{
public EntityShip EntityShip { get; protected set; }
/// <summary>
/// Ширина окна
/// </summary>
private int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
private int _pictureHeight;
/// <summary>
/// Левая координата прорисовки автомобиля
/// </summary>
protected int _startPosX;
/// <summary>
/// Верхняя кооридната прорисовки автомобиля
/// </summary>
protected int _startPosY;
/// <summary>
/// Ширина прорисовки автомобиля
/// </summary>
private readonly int _shipWidth = 110;
/// <summary>
/// Высота прорисовки автомобиля
/// </summary>
private readonly int _shipHeight = 65;
/// <summary>
/// Координата X объекта
/// </summary>
public int GetPosX => _startPosX;
/// <summary>
/// Координата Y объекта
/// </summary>
public int GetPosY => _startPosY;
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth => _shipWidth;
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight => _shipHeight;
public bool CanMove(Direction direction)
{
if(EntityShip == null) return false;
switch(direction)
{
case Direction.Left:
return _startPosX - EntityShip.Step > 0;
case Direction.Right:
return _startPosX + _shipWidth + EntityShip.Step < _pictureWidth;
case Direction.Up:
return _startPosY - EntityShip.Step > 0;
case Direction.Down:
return _startPosY + _shipHeight+ EntityShip.Step < _pictureHeight;
default:
return false;
}
}
public DrawingShip(int speed, double weight, Color bodyColor, int width, int height)
{
if(width < _shipWidth || height < _shipHeight)
{
return;
}
_pictureWidth = width;
_pictureHeight = height;
EntityShip = new EntityShip(speed, weight, bodyColor);
}
protected DrawingShip(int speed, double weight, Color bodyColor, int width, int height, int shipWidth, int shipHeight)
{
if (width < _shipWidth || height < _shipHeight)
{
return;
}
_pictureWidth = width;
_pictureHeight = height;
_shipHeight = shipHeight;
_shipWidth = shipWidth;
EntityShip = new EntityShip(speed, weight, bodyColor);
}
public void SetPosition(int x, int y)
{
// TODO: Изменение x, y
_startPosX = Math.Min(x, _pictureWidth - _shipWidth);
_startPosY = Math.Min(y, _pictureHeight - _shipHeight);
}
public void MoveTransport(Direction direction)
{
if (!CanMove(direction) || EntityShip == null)
{
return;
}
switch (direction)
{
//влево
case Direction.Left:
if (_startPosX - EntityShip.Step > 0)
{
_startPosX -= (int)EntityShip.Step;
}
break;
//вверх
case Direction.Up:
if (_startPosY - EntityShip.Step > 0)
{
_startPosY -= (int)EntityShip.Step;
}
break;
// вправо
case Direction.Right:
// TODO: Продумать логику
if (_startPosX + EntityShip.Step + _shipWidth < _pictureWidth)
{
_startPosX += (int)EntityShip.Step;
}
break;
//вниз
case Direction.Down:
// TODO: Продумать логику
if (_startPosY + EntityShip.Step + _shipHeight< _pictureHeight)
{
_startPosY += (int)EntityShip.Step;
}
break;
}
}
public virtual void DrawShip(Graphics g)
{
if (EntityShip == null)
{
return;
}
Pen pen = new Pen(Color.Black);
Brush brBody = new SolidBrush(EntityShip.BodyColor);
// заполнение борта
g.FillPolygon(brBody, new PointF[]
{
new PointF(_startPosX, _startPosY+45),
new PointF(_startPosX+20, _startPosY+65),
new PointF(_startPosX+90, _startPosY+65),
new PointF(_startPosX+110, _startPosY+45),
new PointF(_startPosX, _startPosY+45)
});
//борт корабля контур
g.DrawLines(pen, new Point[] {
new Point(_startPosX, _startPosY+45),
new Point(_startPosX+20, _startPosY+65),
new Point(_startPosX+90, _startPosY+65),
new Point(_startPosX+110, _startPosY+45),
new Point(_startPosX, _startPosY+45)});
//рисунок на борту
g.DrawLine(pen, _startPosX + 23, _startPosY + 60, _startPosX + 27, _startPosY + 60);
g.DrawLine(pen, _startPosX + 25, _startPosY + 50, _startPosX + 25, _startPosY + 60);
g.DrawLine(pen, _startPosX + 20, _startPosY + 55, _startPosX + 30, _startPosY + 55);
//контейнеры
}
}
}

View File

@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Lab1ContainersShip.DrawingObjects;
namespace Lab1ContainersShip.MovementStrategy
{
public class DrawningObjectShip : IMoveableObject
{
private readonly DrawingShip _drawingShip = null;
public DrawningObjectShip(DrawingShip drawingShip)
{
_drawingShip = drawingShip;
}
public ObjectParameters GetObjectPosition
{
get
{
if (_drawingShip == null || _drawingShip.EntityShip ==
null)
{
return null;
}
return new ObjectParameters(_drawingShip.GetPosX,
_drawingShip.GetPosY, _drawingShip.GetWidth, _drawingShip.GetHeight);
}
}
public int GetStep => (int)(_drawingShip?.EntityShip.Step ?? 0);
public bool CheckCanMove(Direction direction) =>
_drawingShip?.CanMove(direction) ?? false;
public void MoveObject(Direction direction) =>
_drawingShip?.MoveTransport(direction);
}
}

View File

@ -5,28 +5,11 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Lab1ContainersShip namespace Lab1ContainersShip.Entities
{ {
public class EntityContainerShip internal class EntityContainerShip : EntityShip
{ {
/// <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>
/// Признак (опция) наличия крана /// Признак (опция) наличия крана
/// </summary> /// </summary>
@ -35,13 +18,9 @@ namespace Lab1ContainersShip
/// Признак (опция) наличия контейнеров /// Признак (опция) наличия контейнеров
/// </summary> /// </summary>
public bool Conteiners { get; private set; } public bool Conteiners { get; private set; }
public double Step => (double)Speed * 100 / Weight; public EntityContainerShip(int speed, double weight, Color bodyColor, Color additionalColor,
public void Init(int speed, double weight, Color bodyColor, Color bool crane, bool containers ) : base (speed, weight, bodyColor)
additionalColor, bool crane, bool containers)
{ {
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor; AdditionalColor = additionalColor;
Crane = crane; Crane = crane;
Conteiners = containers; Conteiners = containers;

View File

@ -0,0 +1,46 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lab1ContainersShip.Entities
{
public class EntityShip
{
/// <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>
/// <summary>
/// Признак (опция) наличия крана
/// </summary>
/// <summary>
/// Признак (опция) наличия контейнеров
/// </summary>
public double Step => (double)Speed * 100 / Weight;
public EntityShip(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}
}

View File

@ -1,98 +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 Lab1ContainersShip
{
public partial class Form1 : Form
{
private DrawingContainerShip _drawningShip;
public Form1()
{
InitializeComponent();
}
/// <summary>
/// Поле-объект для прорисовки объекта
/// </summary>
/// <summary>
/// Инициализация формы
/// </summary>
/// <summary>
/// Метод прорисовки машины
/// </summary>
private void Draw()
{
if (_drawningShip == null)
{
return;
}
Bitmap bmp = new Bitmap (pictureBox1.Width,
pictureBox1.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningShip.DrawShip(gr);
pictureBox1.Image = bmp;
}
private void buttonCreate_Click(object sender, EventArgs e)
{
Random random = new Random();
_drawningShip = new DrawingContainerShip();
EntityContainerShip _entitycont = new EntityContainerShip();
/*_entitycont.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)));*/
_drawningShip.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)),
pictureBox1.Width, pictureBox1.Height);
//_drawningShip.Init(_entitycont, pictureBox1.Width, pictureBox1.Height);
_drawningShip.SetPosition(random.Next(10, 100),
random.Next(10, 100));
Draw();
}
private void buttonMove_Click(object sender, EventArgs e)
{
if (_drawningShip == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
switch (name)
{
case "buttonUp":
_drawningShip.MoveTransport(Direction.Up);
break;
case "buttonDown":
_drawningShip.MoveTransport(Direction.Down);
break;
case "buttonLeft":
_drawningShip.MoveTransport(Direction.Left);
break;
case "buttonRight":
_drawningShip.MoveTransport(Direction.Right);
break;
}
Draw();
}
}
}

View File

@ -1,6 +1,6 @@
namespace Lab1ContainersShip namespace Lab1ContainersShip
{ {
partial class Form1 partial class FormContainerShip
{ {
/// <summary> /// <summary>
/// Обязательная переменная конструктора. /// Обязательная переменная конструктора.
@ -28,26 +28,18 @@
/// </summary> /// </summary>
private void InitializeComponent() private void InitializeComponent()
{ {
this.buttonCreate = new System.Windows.Forms.Button();
this.buttonUp = new System.Windows.Forms.Button(); this.buttonUp = new System.Windows.Forms.Button();
this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.buttonRight = new System.Windows.Forms.Button(); this.buttonRight = new System.Windows.Forms.Button();
this.buttonLeft = new System.Windows.Forms.Button(); this.buttonLeft = new System.Windows.Forms.Button();
this.buttonDown = new System.Windows.Forms.Button(); this.buttonDown = new System.Windows.Forms.Button();
this.comboBoxStrategy = new System.Windows.Forms.ComboBox();
this.buttonStep = new System.Windows.Forms.Button();
this.buttonCreateContainerShip = new System.Windows.Forms.Button();
this.buttonCreateShip = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout(); this.SuspendLayout();
// //
// 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(12, 426);
this.buttonCreate.Name = "buttonCreate";
this.buttonCreate.Size = new System.Drawing.Size(75, 23);
this.buttonCreate.TabIndex = 1;
this.buttonCreate.Text = "создать";
this.buttonCreate.UseVisualStyleBackColor = true;
this.buttonCreate.Click += new System.EventHandler(this.buttonCreate_Click);
//
// buttonUp // buttonUp
// //
this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
@ -69,7 +61,6 @@
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pictureBox1.TabIndex = 0; this.pictureBox1.TabIndex = 0;
this.pictureBox1.TabStop = false; this.pictureBox1.TabStop = false;
this.pictureBox1.Click += new System.EventHandler(this.buttonMove_Click);
// //
// buttonRight // buttonRight
// //
@ -107,16 +98,61 @@
this.buttonDown.UseVisualStyleBackColor = true; this.buttonDown.UseVisualStyleBackColor = true;
this.buttonDown.Click += new System.EventHandler(this.buttonMove_Click); this.buttonDown.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[] {
"MoveToCenter",
"MoveToRight-Down"});
this.comboBoxStrategy.Location = new System.Drawing.Point(751, 12);
this.comboBoxStrategy.Name = "comboBoxStrategy";
this.comboBoxStrategy.Size = new System.Drawing.Size(121, 21);
this.comboBoxStrategy.TabIndex = 6;
//
// buttonStep
//
this.buttonStep.Location = new System.Drawing.Point(797, 39);
this.buttonStep.Name = "buttonStep";
this.buttonStep.Size = new System.Drawing.Size(75, 23);
this.buttonStep.TabIndex = 7;
this.buttonStep.Text = "шаг";
this.buttonStep.UseVisualStyleBackColor = true;
this.buttonStep.Click += new System.EventHandler(this.buttonStep_Click);
//
// buttonCreateContainerShip
//
this.buttonCreateContainerShip.Location = new System.Drawing.Point(12, 411);
this.buttonCreateContainerShip.Name = "buttonCreateContainerShip";
this.buttonCreateContainerShip.Size = new System.Drawing.Size(97, 38);
this.buttonCreateContainerShip.TabIndex = 8;
this.buttonCreateContainerShip.Text = "создать контейнеровоз";
this.buttonCreateContainerShip.UseVisualStyleBackColor = true;
this.buttonCreateContainerShip.Click += new System.EventHandler(this.buttonCreateContainerShip_Click);
//
// buttonCreateShip
//
this.buttonCreateShip.Location = new System.Drawing.Point(115, 411);
this.buttonCreateShip.Name = "buttonCreateShip";
this.buttonCreateShip.Size = new System.Drawing.Size(94, 38);
this.buttonCreateShip.TabIndex = 9;
this.buttonCreateShip.Text = "создать кораблик";
this.buttonCreateShip.UseVisualStyleBackColor = true;
this.buttonCreateShip.Click += new System.EventHandler(this.buttonCreateShip_Click);
//
// Form1 // Form1
// //
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(884, 461); this.ClientSize = new System.Drawing.Size(884, 461);
this.Controls.Add(this.buttonCreateShip);
this.Controls.Add(this.buttonCreateContainerShip);
this.Controls.Add(this.buttonStep);
this.Controls.Add(this.comboBoxStrategy);
this.Controls.Add(this.buttonDown); this.Controls.Add(this.buttonDown);
this.Controls.Add(this.buttonLeft); this.Controls.Add(this.buttonLeft);
this.Controls.Add(this.buttonRight); this.Controls.Add(this.buttonRight);
this.Controls.Add(this.buttonUp); this.Controls.Add(this.buttonUp);
this.Controls.Add(this.buttonCreate);
this.Controls.Add(this.pictureBox1); this.Controls.Add(this.pictureBox1);
this.Name = "Form1"; this.Name = "Form1";
this.Text = "контейнеровоз"; this.Text = "контейнеровоз";
@ -129,11 +165,14 @@
#endregion #endregion
private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.Button buttonCreate;
private System.Windows.Forms.Button buttonUp; private System.Windows.Forms.Button buttonUp;
private System.Windows.Forms.Button buttonRight; private System.Windows.Forms.Button buttonRight;
private System.Windows.Forms.Button buttonLeft; private System.Windows.Forms.Button buttonLeft;
private System.Windows.Forms.Button buttonDown; private System.Windows.Forms.Button buttonDown;
private System.Windows.Forms.ComboBox comboBoxStrategy;
private System.Windows.Forms.Button buttonStep;
private System.Windows.Forms.Button buttonCreateContainerShip;
private System.Windows.Forms.Button buttonCreateShip;
} }
} }

View File

@ -0,0 +1,151 @@
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 Lab1ContainersShip.DrawingObjects;
using Lab1ContainersShip.MovementStrategy;
namespace Lab1ContainersShip
{
public partial class FormContainerShip : Form
{
private DrawingShip _drawingShip;
private AbstractStrategy _abstractStrategy;
public FormContainerShip()
{
InitializeComponent();
}
private void Draw()
{
if (_drawingShip == null)
{
return;
}
Bitmap bmp = new Bitmap (pictureBox1.Width,
pictureBox1.Height);
Graphics gr = Graphics.FromImage(bmp);
if(_drawingShip is DrawingShip)
{
(_drawingShip as DrawingShip).DrawShip(gr);
}
else
{
_drawingShip.DrawShip(gr);
}
pictureBox1.Image = bmp;
}
private void buttonMove_Click(object sender, EventArgs e)
{
if (_drawingShip == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
switch (name)
{
case "buttonUp":
_drawingShip.MoveTransport(Direction.Up);
break;
case "buttonDown":
_drawingShip.MoveTransport(Direction.Down);
break;
case "buttonLeft":
_drawingShip.MoveTransport(Direction.Left);
break;
case "buttonRight":
_drawingShip.MoveTransport(Direction.Right);
break;
}
Draw();
}
private void buttonStep_Click(object sender, EventArgs e)
{
if (_drawingShip == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
switch (comboBoxStrategy.SelectedIndex)
{
case 0:
_abstractStrategy = new MoveToCenter();
break;
case 1:
_abstractStrategy = new MoveToBorder();
break;
default:
_abstractStrategy = null;
break;
}
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(new
DrawningObjectShip(_drawingShip), pictureBox1.Width,
pictureBox1.Height);
comboBoxStrategy.Enabled = false;
}
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_abstractStrategy = null;
}
}
private void buttonCreateContainerShip_Click(object sender, EventArgs e)
{
Random random = new Random();
_drawingShip = new DrawingContainerShip(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)),
pictureBox1.Width, pictureBox1.Height);
_drawingShip.SetPosition(random.Next(10, 100), random.Next(10,
100));
Draw();
}
private void buttonCreateShip_Click(object sender, EventArgs e)
{
Random random = new Random();
_drawingShip = new DrawingShip(random.Next(100, 300),
random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256),
random.Next(0, 256)),
pictureBox1.Width, pictureBox1.Height);
_drawingShip.SetPosition(random.Next(10, 100), random.Next(10,
100));
Draw();
}
}
}

View File

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

View File

@ -46,19 +46,28 @@
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="AbstractStrategy.cs" />
<Compile Include="Direction.cs" /> <Compile Include="Direction.cs" />
<Compile Include="DrawingContainerShip.cs" /> <Compile Include="DrawingContainerShip.cs" />
<Compile Include="DrawingShip.cs" />
<Compile Include="DrawningObjectShip.cs" />
<Compile Include="EntityContainerShip.cs" /> <Compile Include="EntityContainerShip.cs" />
<Compile Include="Form1.cs"> <Compile Include="EntityShip.cs" />
<Compile Include="FormContainerShip.cs">
<SubType>Form</SubType> <SubType>Form</SubType>
</Compile> </Compile>
<Compile Include="Form1.Designer.cs"> <Compile Include="FormContainerShip.Designer.cs">
<DependentUpon>Form1.cs</DependentUpon> <DependentUpon>FormContainerShip.cs</DependentUpon>
</Compile> </Compile>
<Compile Include="IMoveableObject.cs" />
<Compile Include="MoveToBorder.cs" />
<Compile Include="MoveToCenter.cs" />
<Compile Include="ObjectParameters.cs" />
<Compile Include="Program.cs" /> <Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<EmbeddedResource Include="Form1.resx"> <Compile Include="Status.cs" />
<DependentUpon>Form1.cs</DependentUpon> <EmbeddedResource Include="FormContainerShip.resx">
<DependentUpon>FormContainerShip.cs</DependentUpon>
</EmbeddedResource> </EmbeddedResource>
<EmbeddedResource Include="Properties\Resources.resx"> <EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator> <Generator>ResXFileCodeGenerator</Generator>

View File

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

View File

@ -16,7 +16,7 @@ namespace Lab1ContainersShip
{ {
Application.EnableVisualStyles(); Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false); Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1()); Application.Run(new FormContainerShip());
} }
} }
} }

View File

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