This commit is contained in:
pnevmoslon1 2024-04-09 05:09:01 +04:00
parent f526a5f2bc
commit 16a64b9ff7
22 changed files with 860 additions and 364 deletions

View File

@ -1,176 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip
{
public class DrawningWarmlyShip
{
public EntityWarmlyShip? EntityWarmlyShip { get; private set; }
private int? _pictureWidth;
private int? _pictureHeight;
private int? _startPosX;
private int? _startPosY;
private readonly int _drawningWarmlyShipWidth = 150;
private readonly int _drawningWarmlyShipHeight = 80;
public void Init(int speed, double weight, Color bodyColor, Color seckondColor, bool fuelHole, bool pipes)
{
EntityWarmlyShip = new EntityWarmlyShip();
EntityWarmlyShip.Init(speed, weight, bodyColor, seckondColor, fuelHole, pipes);
_pictureHeight = null;
_pictureWidth = null;
_startPosX = null;
_startPosY = null;
}
public bool SetPictureSize(int width, int height)
{
if (width > _drawningWarmlyShipWidth && height > _drawningWarmlyShipHeight)
{
_pictureWidth = width;
_pictureHeight = height;
if (_startPosX != null && _startPosY != null)
{
if (_startPosX.Value + _drawningWarmlyShipWidth > _pictureWidth)
{
_startPosX = _pictureWidth - _drawningWarmlyShipWidth;
}
if (_startPosY.Value + _drawningWarmlyShipHeight > _pictureHeight)
{
_startPosY = _pictureHeight - _drawningWarmlyShipHeight;
}
}
return true;
}
return false;
}
public void SetPosition(int x, int y)
{
if (!_pictureHeight.HasValue || !_pictureWidth.HasValue)
{
return;
}
else
{
_startPosX = x;
_startPosY = y;
if (_startPosX < 0) _startPosX = 0;
if (_startPosY < 0) _startPosY = 0;
if (_startPosX + _drawningWarmlyShipWidth > _pictureWidth.Value)
{
_startPosX = _pictureWidth.Value - _drawningWarmlyShipWidth;
}
if (_startPosY + _drawningWarmlyShipHeight > _pictureHeight.Value)
{
_startPosY = _pictureHeight.Value - _drawningWarmlyShipHeight;
}
}
}
public bool MoveTransport(DirectionType direction)
{
if (EntityWarmlyShip == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return false;
}
switch (direction)
{
case DirectionType.Left:
if (_startPosX.Value - EntityWarmlyShip.Step > 0)
{
_startPosX -= (int)EntityWarmlyShip.Step;
}
return true;
case DirectionType.Up:
if (_startPosY.Value - EntityWarmlyShip.Step > 0)
{
_startPosY -= (int)EntityWarmlyShip.Step;
}
return true;
case DirectionType.Right:
if (_startPosX.Value + _drawningWarmlyShipWidth + EntityWarmlyShip.Step < _pictureWidth)
{
_startPosX += (int)EntityWarmlyShip.Step;
}
return true;
case DirectionType.Down:
if (_startPosY.Value + _drawningWarmlyShipHeight + EntityWarmlyShip.Step < _pictureHeight)
{
_startPosY += (int)EntityWarmlyShip.Step;
}
return true;
default : return false;
}
}
public void DrawTransport(Graphics g)
{
if (EntityWarmlyShip == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
// нарисовать корабль
Pen pen = new(Color.Black, 2);
Brush brMain = new SolidBrush(EntityWarmlyShip.BodyColor);
Brush brSecond = new SolidBrush(EntityWarmlyShip.SeckondColor);
// трапеция
Point[] points = new Point[]
{
new Point(_startPosX.Value, _startPosY.Value+50),
new Point(_startPosX.Value + 150, _startPosY.Value+ 50),
new Point(_startPosX.Value + 120, _startPosY.Value + 80),
new Point(_startPosX.Value + 30, _startPosY.Value + 80)
};
g.FillPolygon(brMain, points);
g.DrawPolygon(pen, points);
//палуба
g.FillRectangle(brMain, _startPosX.Value + 25, _startPosY.Value + 30, 100, 20);
g.DrawRectangle(pen, _startPosX.Value + 25, _startPosY.Value + 30, 100, 20);
//якорь
g.DrawLine(pen, _startPosX.Value + 30, _startPosY.Value + 53, _startPosX.Value + 30, _startPosY.Value + 70);
g.DrawLine(pen, _startPosX.Value + 23, _startPosY.Value + 70, _startPosX.Value + 37, _startPosY.Value + 70);
g.DrawLine(pen, _startPosX.Value + 23, _startPosY.Value + 60, _startPosX.Value + 37, _startPosY.Value + 60);
Brush blackBr = new SolidBrush(Color.Black);
//трубы
if (EntityWarmlyShip.Pipes)
{
g.FillRectangle(brSecond, _startPosX.Value + 35, _startPosY.Value, 20, 30);
g.FillRectangle(brSecond, _startPosX.Value + 64, _startPosY.Value, 20, 30);
g.FillRectangle(brSecond, _startPosX.Value + 93, _startPosY.Value, 20, 30);
}
//топливный отсек
if (EntityWarmlyShip.FuelHole)
{
g.FillEllipse(brSecond, _startPosX.Value + 100, _startPosY.Value + 55, 15, 15);
g.DrawEllipse(pen, _startPosX.Value + 100, _startPosY.Value + 55, 15, 15);
}
}
}
}

View File

@ -4,13 +4,14 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace WarmlyShip namespace WarmlyShip.Drawnings
{ {
public enum DirectionType public enum DirectionType
{ {
Up = 1, Up = 1,
Down = 2, Down = 2,
Left = 3, Left = 3,
Right = 4 Right = 4,
Unknow = -1
} }
} }

View File

@ -0,0 +1,185 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WarmlyShip.Entities;
namespace WarmlyShip.Drawnings;
public class DrawningShip
{
public EntityShip? EntityShip { get; protected set; }
private int? _pictureWidth;
private int? _pictureHeight;
protected int? _startPosX;
protected int? _startPosY;
private readonly int _drawningWarmlyShipWidth = 150;
private readonly int _drawningWarmlyShipHeight = 80;
public int? GetPosX => _startPosX;
public int? GetPosY => _startPosY;
public int GetWidth => _drawningWarmlyShipWidth;
public int GetHeight => _drawningWarmlyShipHeight;
private DrawningShip() {
_pictureHeight = null;
_pictureWidth = null;
_startPosX = null;
_startPosY = null;
}
public DrawningShip (int speed, double weight, Color bodyColor) : this()
{
EntityShip = new EntityShip(speed, weight, bodyColor);
}
protected DrawningShip(int drawningWarmlyShipWidth, int drawningWarmlyShipHeigh) : this()
{
_drawningWarmlyShipWidth = drawningWarmlyShipWidth;
_drawningWarmlyShipHeight= drawningWarmlyShipHeigh;
}
public bool SetPictureSize(int width, int height)
{
if (width > _drawningWarmlyShipWidth && height > _drawningWarmlyShipHeight)
{
_pictureWidth = width;
_pictureHeight = height;
if (_startPosX != null && _startPosY != null)
{
if (_startPosX.Value + _drawningWarmlyShipWidth > _pictureWidth)
{
_startPosX = _pictureWidth - _drawningWarmlyShipWidth;
}
if (_startPosY.Value + _drawningWarmlyShipHeight > _pictureHeight)
{
_startPosY = _pictureHeight - _drawningWarmlyShipHeight;
}
}
return true;
}
return false;
}
public void SetPosition(int x, int y)
{
if (!_pictureHeight.HasValue || !_pictureWidth.HasValue)
{
return;
}
else
{
_startPosX = x;
_startPosY = y;
if (_startPosX < 0) _startPosX = 0;
if (_startPosY < 0) _startPosY = 0;
if (_startPosX + _drawningWarmlyShipWidth > _pictureWidth.Value)
{
_startPosX = _pictureWidth.Value - _drawningWarmlyShipWidth;
}
if (_startPosY + _drawningWarmlyShipHeight > _pictureHeight.Value)
{
_startPosY = _pictureHeight.Value - _drawningWarmlyShipHeight;
}
}
}
public bool MoveTransport(DirectionType direction)
{
if (EntityShip == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return false;
}
switch (direction)
{
case DirectionType.Left:
if (_startPosX.Value - EntityShip.Step > 0)
{
_startPosX -= (int)EntityShip.Step;
}
return true;
case DirectionType.Up:
if (_startPosY.Value - EntityShip.Step > 0)
{
_startPosY -= (int)EntityShip.Step;
}
return true;
case DirectionType.Right:
if (_startPosX.Value + _drawningWarmlyShipWidth + EntityShip.Step < _pictureWidth)
{
_startPosX += (int)EntityShip.Step;
}
return true;
case DirectionType.Down:
if (_startPosY.Value + _drawningWarmlyShipHeight + EntityShip.Step < _pictureHeight)
{
_startPosY += (int)EntityShip.Step;
}
return true;
default: return false;
}
}
public virtual void DrawTransport(Graphics g)
{
if (EntityShip == null || !_startPosX.HasValue || !_startPosY.HasValue)
{
return;
}
// нарисовать корабль
Pen pen = new(Color.Black, 2);
Brush brMain = new SolidBrush(EntityShip.BodyColor);
// трапеция
Point[] points = new Point[]
{
new Point(_startPosX.Value, _startPosY.Value+20),
new Point(_startPosX.Value + 150, _startPosY.Value+ 20),
new Point(_startPosX.Value + 120, _startPosY.Value + 50),
new Point(_startPosX.Value + 30, _startPosY.Value + 50)
};
g.FillPolygon(brMain, points);
g.DrawPolygon(pen, points);
//палуба
g.FillRectangle(brMain, _startPosX.Value + 25, _startPosY.Value, 100, 20);
g.DrawRectangle(pen, _startPosX.Value + 25, _startPosY.Value, 100, 20);
//якорь
g.DrawLine(pen, _startPosX.Value + 30, _startPosY.Value + 23, _startPosX.Value + 30, _startPosY.Value + 40);
g.DrawLine(pen, _startPosX.Value + 23, _startPosY.Value + 40, _startPosX.Value + 37, _startPosY.Value + 40);
g.DrawLine(pen, _startPosX.Value + 23, _startPosY.Value + 30, _startPosX.Value + 37, _startPosY.Value + 30);
}
}

View File

@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WarmlyShip.Entities;
namespace WarmlyShip.Drawnings
{
public class DrawningWarmlyShip : DrawningShip
{
public DrawningWarmlyShip(int speed, double weight, Color bodyColor, Color seckondColor, bool fuelHole, bool pipes) : base(150, 80)
{
EntityShip = new EntityWarmlyShip(speed, weight, bodyColor, seckondColor, fuelHole, pipes);
}
public override void DrawTransport(Graphics g)
{
if (EntityShip == null || !_startPosX.HasValue || !_startPosY.HasValue || EntityShip is not EntityWarmlyShip warmlyShip)
{
return;
}
_startPosY += 30;
base.DrawTransport(g);
_startPosY -= 30;
Pen pen = new(Color.Black, 2);
Brush brMain = new SolidBrush(EntityShip.BodyColor);
Brush brSecond = new SolidBrush(warmlyShip.SeckondColor);
//трубы
if (warmlyShip.Pipes)
{
g.FillRectangle(brSecond, _startPosX.Value + 35, _startPosY.Value, 20, 30);
g.FillRectangle(brSecond, _startPosX.Value + 64, _startPosY.Value, 20, 30);
g.FillRectangle(brSecond, _startPosX.Value + 93, _startPosY.Value, 20, 30);
}
//топливный отсек
if (warmlyShip.FuelHole)
{
g.FillEllipse(brSecond, _startPosX.Value + 100, _startPosY.Value + 55, 15, 15);
g.DrawEllipse(pen, _startPosX.Value + 100, _startPosY.Value + 55, 15, 15);
}
}
}
}

View File

@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip.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; }
public double Step => Speed * 100 / Weight;
public EntityShip (int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}

View File

@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip.Entities;
public class EntityWarmlyShip : EntityShip
{
/// <summary>
/// доп. цвет
/// </summary>
public Color SeckondColor { get; private set; }
/// <summary>
/// признак наличия отсека для топлива
/// </summary>
public bool FuelHole { get; private set; }
/// <summary>
/// Признак наличия трубы
/// </summary>
public bool Pipes { get; private set; }
/// <summary>
///
/// </summary>
/// <param name="speed"> скорость </param>
/// <param name="weight">вес</param>
/// <param name="bodyColor">основной цвет</param>
/// <param name="seckondColor">доп. цвет</param>
/// <param name="fuelHole">признак наличия отсека для топлива</param>
/// <param name="pipes">признак наличия трубы</param>
public EntityWarmlyShip (int speed, double weight, Color bodyColor, Color seckondColor, bool fuelHole, bool pipes) : base (speed, weight, bodyColor)
{
SeckondColor = seckondColor;
FuelHole = fuelHole;
Pipes = pipes;
}
}

View File

@ -1,62 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip
{
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 SeckondColor { get; private set; }
/// <summary>
/// признак наличия отсека для топлива
/// </summary>
public bool FuelHole { get; private set; }
/// <summary>
/// Признак наличия трубы
/// </summary>
public bool Pipes { get; private set; }
/// <summary>
///
/// </summary>
/// <param name="speed"> скорость </param>
/// <param name="weight">вес</param>
/// <param name="bodyColor">основной цвет</param>
/// <param name="seckondColor">доп. цвет</param>
/// <param name="fuelHole">признак наличия отсека для топлива</param>
/// <param name="pipes">признак наличия трубы</param>
public void Init(int speed, double weight, Color bodyColor, Color seckondColor, bool fuelHole, bool pipes)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
SeckondColor = seckondColor;
FuelHole = fuelHole;
Pipes = pipes;
}
public double Step => Speed * 100 / Weight;
}
}

View File

@ -1,6 +1,6 @@
namespace WarmlyShip namespace WarmlyShip
{ {
partial class pictureBoxShips partial class FormShips
{ {
/// <summary> /// <summary>
/// Required designer variable. /// Required designer variable.
@ -28,23 +28,26 @@
/// </summary> /// </summary>
private void InitializeComponent() private void InitializeComponent()
{ {
pictureBox1 = new PictureBox(); pictureBoxShips = new PictureBox();
buttonDown = new Button(); buttonDown = new Button();
buttonUp = new Button(); buttonUp = new Button();
buttonRight = new Button(); buttonRight = new Button();
buttonLeft = new Button(); buttonLeft = new Button();
buttonCreate = new Button(); buttonCreateWarmlyShip = new Button();
((System.ComponentModel.ISupportInitialize)pictureBox1).BeginInit(); buttonCreateShip = new Button();
comboBoxStrategy = new ComboBox();
buttonStrategyStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxShips).BeginInit();
SuspendLayout(); SuspendLayout();
// //
// pictureBox1 // pictureBoxShips
// //
pictureBox1.Dock = DockStyle.Fill; pictureBoxShips.Dock = DockStyle.Fill;
pictureBox1.Location = new Point(0, 0); pictureBoxShips.Location = new Point(0, 0);
pictureBox1.Name = "pictureBox1"; pictureBoxShips.Name = "pictureBoxShips";
pictureBox1.Size = new Size(854, 493); pictureBoxShips.Size = new Size(854, 493);
pictureBox1.TabIndex = 0; pictureBoxShips.TabIndex = 0;
pictureBox1.TabStop = false; pictureBoxShips.TabStop = false;
// //
// buttonDown // buttonDown
// //
@ -94,42 +97,79 @@
buttonLeft.UseVisualStyleBackColor = true; buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.Click += ButtonMove_Click; buttonLeft.Click += ButtonMove_Click;
// //
// buttonCreate // buttonCreateWarmlyShip
// //
buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; buttonCreateWarmlyShip.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreate.Location = new Point(17, 458); buttonCreateWarmlyShip.Location = new Point(12, 458);
buttonCreate.Name = "buttonCreate"; buttonCreateWarmlyShip.Name = "buttonCreateWarmlyShip";
buttonCreate.Size = new Size(75, 23); buttonCreateWarmlyShip.Size = new Size(161, 23);
buttonCreate.TabIndex = 6; buttonCreateWarmlyShip.TabIndex = 6;
buttonCreate.Text = "создать"; buttonCreateWarmlyShip.Text = "создать пароход";
buttonCreate.UseVisualStyleBackColor = true; buttonCreateWarmlyShip.UseVisualStyleBackColor = true;
buttonCreate.Click += ButtonCreate_Click; buttonCreateWarmlyShip.Click += buttonCreate_Click;
// //
// pictureBoxShips // buttonCreateShip
//
buttonCreateShip.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreateShip.Location = new Point(179, 458);
buttonCreateShip.Name = "buttonCreateShip";
buttonCreateShip.Size = new Size(161, 23);
buttonCreateShip.TabIndex = 11;
buttonCreateShip.Text = "создать лодку";
buttonCreateShip.UseVisualStyleBackColor = true;
buttonCreateShip.Click += buttonCreateShip_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "К центру", "К краю" });
comboBoxStrategy.Location = new Point(721, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(121, 23);
comboBoxStrategy.TabIndex = 12;
//
// buttonStrategyStep
//
buttonStrategyStep.Location = new Point(766, 41);
buttonStrategyStep.Name = "buttonStrategyStep";
buttonStrategyStep.Size = new Size(75, 23);
buttonStrategyStep.TabIndex = 13;
buttonStrategyStep.Text = "шаг";
buttonStrategyStep.UseVisualStyleBackColor = true;
buttonStrategyStep.Click += buttonStrategyStep_Click;
//
// FormShips
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(854, 493); ClientSize = new Size(854, 493);
Controls.Add(buttonStrategyStep);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonCreateShip);
Controls.Add(buttonDown); Controls.Add(buttonDown);
Controls.Add(buttonUp); Controls.Add(buttonUp);
Controls.Add(buttonRight); Controls.Add(buttonRight);
Controls.Add(buttonLeft); Controls.Add(buttonLeft);
Controls.Add(buttonCreate); Controls.Add(buttonCreateWarmlyShip);
Controls.Add(pictureBox1); Controls.Add(pictureBoxShips);
Name = "pictureBoxShips"; Name = "FormShips";
StartPosition = FormStartPosition.CenterScreen; StartPosition = FormStartPosition.CenterScreen;
Text = "pictureBoxShips"; Text = "pictureBoxShips";
((System.ComponentModel.ISupportInitialize)pictureBox1).EndInit(); ((System.ComponentModel.ISupportInitialize)pictureBoxShips).EndInit();
ResumeLayout(false); ResumeLayout(false);
} }
#endregion #endregion
private PictureBox pictureBox1; private PictureBox pictureBoxShips;
private Button buttonDown; private Button buttonDown;
private Button buttonUp; private Button buttonUp;
private Button buttonRight; private Button buttonRight;
private Button buttonLeft; private Button buttonLeft;
private Button buttonCreate; private Button buttonCreateWarmlyShip;
private Button buttonCreateShip;
private ComboBox comboBoxStrategy;
private Button buttonStrategyStep;
} }
} }

View File

@ -0,0 +1,144 @@
using ProjectShip.MovementStrategy;
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.Drawnings;
using WarmlyShip.MovementStrategy;
namespace WarmlyShip
{
public partial class FormShips : Form
{
private DrawningShip? _drawningShip;
private AbstractStrategy? _strategy;
public FormShips()
{
InitializeComponent();
_strategy = null;
}
private void Draw()
{
if (_drawningShip == null)
{
return;
}
Bitmap bmp = new(pictureBoxShips.Width, pictureBoxShips.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningShip.DrawTransport(gr);
pictureBoxShips.Image = bmp;
}
private void CreateObject(string type)
{
Random random = new();
switch (type)
{
case nameof(DrawningShip):
_drawningShip = new DrawningShip(random.Next(100, 300), random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)));
break;
case nameof(DrawningWarmlyShip):
_drawningShip = new DrawningWarmlyShip(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)));
break;
default:
return;
}
_strategy = null;
_drawningShip.SetPictureSize(pictureBoxShips.Width, pictureBoxShips.Height);
_drawningShip.SetPosition(random.Next(10, 100), random.Next(10, 100));
comboBoxStrategy.Enabled = true;
Draw();
}
private void buttonCreate_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningWarmlyShip));
private void buttonCreateShip_Click(object sender, EventArgs e) => CreateObject(nameof(DrawningShip));
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawningShip == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
bool result = false;
switch (name)
{
case "buttonUp":
result = _drawningShip.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
result = _drawningShip.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
result = _drawningShip.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
result = _drawningShip.MoveTransport(DirectionType.Right);
break;
}
if (result)
{
Draw();
}
}
private void buttonStrategyStep_Click(object sender, EventArgs e)
{
if (_drawningShip == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_strategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_strategy == null)
{
return;
}
_strategy.SetData(new MoveableShip(_drawningShip), pictureBoxShips.Width, pictureBoxShips.Height);
}
if (_strategy == null)
{
return;
}
comboBoxStrategy.Enabled = false;
_strategy.MakeStep();
Draw();
if (_strategy.GetStatus() == StrategyStatus.Finish)
{
comboBoxStrategy.Enabled = true;
_strategy = null;
}
}
}
}

View File

@ -0,0 +1,80 @@
using WarmlyShip.MovementStrategy;
namespace WarmlyShip.MovementStrategy;
public abstract class AbstractStrategy
{
private IMoveableObject? _moveableObject;
private StrategyStatus _state = StrategyStatus.NotInit;
protected int FieldWidth { get; private set; }
protected int FieldHeight { get; private set; }
public StrategyStatus GetStatus() { return _state; }
public void SetData(IMoveableObject moveableObject, int width, int height)
{
if (moveableObject == null)
{
_state = StrategyStatus.NotInit;
return;
}
_state = StrategyStatus.InProgress;
_moveableObject = moveableObject;
FieldWidth = width;
FieldHeight = height;
}
public void MakeStep()
{
if (_state != StrategyStatus.InProgress)
{
return;
}
if (IsTargetDestination())
{
_state = StrategyStatus.Finish;
return;
}
MoveToTarget();
}
protected bool MoveLeft() => MoveTo(MovementDirection.Left);
protected bool MoveRight() => MoveTo(MovementDirection.Right);
protected bool MoveUp() => MoveTo(MovementDirection.Up);
protected bool MoveDown() => MoveTo(MovementDirection.Down);
protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectPosition;
protected int? GetStep()
{
if (_state != StrategyStatus.InProgress)
{
return null;
}
return _moveableObject.GetStep;
}
protected abstract void MoveToTarget();
protected abstract bool IsTargetDestination();
private bool MoveTo(MovementDirection movementDirection)
{
if (_state != StrategyStatus.InProgress)
{
return false;
}
return _moveableObject?.TryMoveObject(movementDirection) ?? false;
}
}

View File

@ -0,0 +1,11 @@
using WarmlyShip.MovementStrategy;
namespace WarmlyShip.MovementStrategy;
public interface IMoveableObject
{
ObjectParameters? GetObjectPosition { get; }
int GetStep { get; }
bool TryMoveObject(MovementDirection direction);
}

View File

@ -0,0 +1,37 @@
namespace WarmlyShip.MovementStrategy;
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestination()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.LeftBorder - GetStep() <= 0 || objParams.RightBorder + GetStep() >= FieldWidth ||
objParams.TopBorder - GetStep() <= 0 || objParams.ObjectMiddleVertical + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
ObjectParameters? objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
int diffX = objParams.RightBorder - FieldWidth;
if (Math.Abs(diffX) > GetStep())
{
MoveRight();
}
int diffY = objParams.BottomBorder - FieldHeight;
if (Math.Abs(diffY) > GetStep())
{
MoveDown();
}
}
}

View File

@ -0,0 +1,54 @@
using WarmlyShip.MovementStrategy;
namespace WarmlyShip.MovementStrategy;
public class MoveToCenter : AbstractStrategy
{
protected override bool IsTargetDestination()
{
ObjectParameters? objParams = GetObjectParameters;
if(objParams == null)
{
return false;
}
return objParams.ObjectMiddleHorizontal - GetStep() <= FieldWidth / 2 && objParams.ObjectMiddleHorizontal + GetStep() >= FieldWidth / 2
&&
objParams.ObjectMiddleVertical - GetStep() <= FieldHeight / 2 && objParams.ObjectMiddleVertical + GetStep() >= FieldHeight / 2;
}
protected override void MoveToTarget()
{
ObjectParameters? objParams = GetObjectParameters;
if(objParams == null)
{
return;
}
int diffX = objParams.ObjectMiddleHorizontal - FieldWidth / 2;
if (Math.Abs(diffX) > GetStep())
{
if (diffX > 0)
{
MoveLeft();
}
else
{
MoveRight();
}
}
int diffY = objParams.ObjectMiddleVertical - FieldHeight / 2;
if (Math.Abs(diffY) > GetStep())
{
if (diffY > 0)
{
MoveUp();
}
else
{
MoveDown();
}
}
}
}

View File

@ -0,0 +1,53 @@
using WarmlyShip.MovementStrategy;
using WarmlyShip.Drawnings;
using WarmlyShip.MovementStrategy;
namespace ProjectShip.MovementStrategy;
public class MoveableShip : IMoveableObject
{
private readonly DrawningShip? _drawningShip = null;
public MoveableShip(DrawningShip ship)
{
_drawningShip = ship;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_drawningShip == null || _drawningShip.EntityShip == null || !_drawningShip.GetPosX.HasValue || !_drawningShip.GetPosY.HasValue)
{
return null;
}
return new ObjectParameters(_drawningShip.GetPosX.Value, _drawningShip.GetPosY.Value, _drawningShip.GetWidth, _drawningShip.GetHeight);
}
}
public int GetStep => (int)(_drawningShip?.EntityShip?.Step ?? 0);
public bool TryMoveObject(MovementDirection direction)
{
if(_drawningShip == null || _drawningShip.EntityShip == null)
{
return false;
}
return _drawningShip.MoveTransport(GetDirectionType(direction));
}
private static DirectionType GetDirectionType(MovementDirection direction)
{
return direction switch
{
MovementDirection.Left => DirectionType.Left,
MovementDirection.Right => DirectionType.Right,
MovementDirection.Up => DirectionType.Up,
MovementDirection.Down => DirectionType.Down,
_ => DirectionType.Unknow,
};
}
}

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 MovementDirection
{
Up = 1,
Down = 2,
Left = 3,
Right = 4
}

View File

@ -0,0 +1,32 @@

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 BottomBorder => _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

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

View File

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

View File

@ -1,10 +1,10 @@
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
// <auto-generated> // <auto-generated>
// Этот код создан программой. // This code was generated by a tool.
// Исполняемая версия:4.0.30319.42000 // Runtime Version:4.0.30319.42000
// //
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае // Changes to this file may cause incorrect behavior and will be lost if
// повторной генерации кода. // the code is regenerated.
// </auto-generated> // </auto-generated>
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
@ -13,12 +13,12 @@ namespace WarmlyShip.Properties {
/// <summary> /// <summary>
/// Класс ресурса со строгой типизацией для поиска локализованных строк и т.д. /// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary> /// </summary>
// Этот класс создан автоматически классом StronglyTypedResourceBuilder // This class was auto-generated by the StronglyTypedResourceBuilder
// с помощью такого средства, как ResGen или Visual Studio. // class via a tool like ResGen or Visual Studio.
// Чтобы добавить или удалить член, измените файл .ResX и снова запустите ResGen // To add or remove a member, edit your .ResX file then rerun ResGen
// с параметром /str или перестройте свой проект VS. // with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
@ -33,7 +33,7 @@ namespace WarmlyShip.Properties {
} }
/// <summary> /// <summary>
/// Возвращает кэшированный экземпляр ResourceManager, использованный этим классом. /// Returns the cached ResourceManager instance used by this class.
/// </summary> /// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager { internal static global::System.Resources.ResourceManager ResourceManager {
@ -47,8 +47,8 @@ namespace WarmlyShip.Properties {
} }
/// <summary> /// <summary>
/// Перезаписывает свойство CurrentUICulture текущего потока для всех /// Overrides the current thread's CurrentUICulture property for all
/// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией. /// resource lookups using this strongly typed resource class.
/// </summary> /// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture { internal static global::System.Globalization.CultureInfo Culture {
@ -61,7 +61,7 @@ namespace WarmlyShip.Properties {
} }
/// <summary> /// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap. /// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary> /// </summary>
internal static System.Drawing.Bitmap arrowDown { internal static System.Drawing.Bitmap arrowDown {
get { get {
@ -71,7 +71,7 @@ namespace WarmlyShip.Properties {
} }
/// <summary> /// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap. /// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary> /// </summary>
internal static System.Drawing.Bitmap arrowLeft { internal static System.Drawing.Bitmap arrowLeft {
get { get {
@ -81,7 +81,7 @@ namespace WarmlyShip.Properties {
} }
/// <summary> /// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap. /// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary> /// </summary>
internal static System.Drawing.Bitmap arrowRight { internal static System.Drawing.Bitmap arrowRight {
get { get {
@ -91,7 +91,7 @@ namespace WarmlyShip.Properties {
} }
/// <summary> /// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap. /// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary> /// </summary>
internal static System.Drawing.Bitmap arrowUp { internal static System.Drawing.Bitmap arrowUp {
get { get {

View File

@ -8,6 +8,12 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<Compile Remove="NewFolder\**" />
<EmbeddedResource Remove="NewFolder\**" />
<None Remove="NewFolder\**" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>

View File

@ -1,80 +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 WarmlyShip
{
public partial class pictureBoxShips : Form
{
private DrawningWarmlyShip? _drawningWarmlyShip;
public pictureBoxShips()
{
InitializeComponent();
}
private void Draw()
{
if (_drawningWarmlyShip == null)
{
return;
}
Bitmap bmp = new(pictureBox1.Width, pictureBox1.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawningWarmlyShip.DrawTransport(gr);
pictureBox1.Image = bmp;
}
private void ButtonCreate_Click(object sender, EventArgs e)
{
Random random = new();
_drawningWarmlyShip = new DrawningWarmlyShip();
_drawningWarmlyShip.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)));
_drawningWarmlyShip.SetPictureSize(pictureBox1.Width, pictureBox1.Height);
_drawningWarmlyShip.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_drawningWarmlyShip == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
bool result = false;
switch (name)
{
case "buttonUp":
result = _drawningWarmlyShip.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
result = _drawningWarmlyShip.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
result = _drawningWarmlyShip.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
result = _drawningWarmlyShip.MoveTransport(DirectionType.Right);
break;
}
if (result)
{
Draw();
}
}
}
}