Compare commits

..

No commits in common. "laba2" and "main" have entirely different histories.
laba2 ... main

25 changed files with 77 additions and 1136 deletions

View File

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

View File

@ -8,19 +8,4 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
</Project>

View File

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

View File

@ -1,153 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AircraftCarrier.Entities;
namespace AircraftCarrier.DrawningObjects
{
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
public class DrawningAircraft
{
/// Класс-сущность
public EntityAircraft? EntityAircraft { get; protected set; }
/// Ширина окна
private int _pictureWidth;
/// Высота окна
private int _pictureHeight;
protected int _startPosX;
protected int _startPosY;
protected readonly int _AircraftWidth = 164;
protected readonly int _AircraftHeight = 40;
/// Координата X объекта
public int GetPosX => _startPosX;
/// Координата Y объекта
public int GetPosY => _startPosY;
/// Ширина объекта
public int GetWidth => _AircraftWidth;
/// Высота объекта
public int GetHeight => _AircraftHeight;
/// Проверка, что объект может переместится по указанному направлению
/// <param name="direction">Направление</param>
/// <returns>true - можно переместится по указанному направлению</returns>
public bool CanMove(Direction direction)
{
if (EntityAircraft == null)
{
return false;
}
return direction switch
{
//влево
Direction.Left => _startPosX - EntityAircraft.Step > 0,
//вверх
Direction.Up => _startPosY - EntityAircraft.Step > 0,
// вправо
Direction.Right => _startPosX + EntityAircraft.Step + _AircraftWidth < _pictureWidth,
//вниз
Direction.Down => _startPosY + EntityAircraft.Step + _AircraftHeight < _pictureHeight,
_ => false
};
}
/// Изменение направления перемещения
/// <param name="direction">Направление</param>
public void MoveTransport(Direction direction)
{
if (!CanMove(direction) || EntityAircraft == null)
{
return;
}
switch (direction)
{
//влево
case Direction.Left:
_startPosX -= (int)EntityAircraft.Step;
break;
//вверх
case Direction.Up:
_startPosY -= (int)EntityAircraft.Step;
break;
// вправо
case Direction.Right:
_startPosX += (int)EntityAircraft.Step;
break;
//вниз
case Direction.Down:
_startPosY += (int)EntityAircraft.Step;
break;
}
}
/// Конструктор
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public DrawningAircraft(int speed, double weight, Color bodyColor, int
width, int height)
{
if (width < _AircraftWidth || height < _AircraftHeight)
{
return;
}
_pictureWidth = width;
_pictureHeight = height;
EntityAircraft = new EntityAircraft(speed, weight, bodyColor);
}
/// Конструктор
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Основной цвет</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
/// <param name="carWidth">Ширина прорисовки автомобиля</param>
/// <param name="carHeight">Высота прорисовки автомобиля</param>
protected DrawningAircraft(int speed, double weight, Color bodyColor,int
width, int height, int AircraftWidth, int AircraftHeight)
{
if (width < _AircraftWidth || height < _AircraftHeight)
{
return;
}
_pictureWidth = width;
_pictureHeight = height;
_AircraftWidth = AircraftWidth;
_AircraftHeight = AircraftHeight;
EntityAircraft = new EntityAircraft(speed, weight, bodyColor);
}
/// Установка позиции
public void SetPosition(int x, int y)
{
_startPosX = x;
_startPosY = y;
if (_startPosX < 0 || _startPosY < 0 || _startPosX > (_pictureWidth - _AircraftWidth) || _startPosY > (_pictureHeight - _AircraftHeight))
{
_startPosX = 50;
_startPosY = 50;
}
}
/// Изменение направления перемещения
/// Прорисовка объекта
public virtual void DrawTransport(Graphics g)
{
if (EntityAircraft == null)
{
return;
}
Pen pen = new(Color.Black);
Brush budyBrush = new SolidBrush(EntityAircraft.BodyColor);
g.DrawLine(pen, _startPosX + 4, _startPosY, _startPosX + 124, _startPosY);
g.DrawLine(pen, _startPosX + 124, _startPosY, _startPosX + 164, _startPosY + 20);
g.DrawLine(pen, _startPosX + 164, _startPosY + 20, _startPosX + 124, _startPosY + 40);
g.DrawLine(pen, _startPosX + 164, _startPosY + 20, _startPosX + 124, _startPosY + 40);
g.DrawLine(pen, _startPosX + 124, _startPosY + 40, _startPosX + 4, _startPosY + 40);
g.DrawLine(pen, _startPosX + 4, _startPosY + 40, _startPosX + 4, _startPosY);
g.FillRectangle(budyBrush, _startPosX, _startPosY + 6, 4, 12);
g.FillRectangle(budyBrush, _startPosX, _startPosY + 24, 4, 12);
g.DrawEllipse(pen, _startPosX + 115, _startPosY + 13, 14, 14);
g.DrawRectangle(pen, _startPosX + 63, _startPosY + 13, 27, 14);
g.DrawRectangle(pen, _startPosX + 90, _startPosY + 9, 14, 22);
}
}
}

View File

@ -1,43 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AircraftCarrier.Entities;
namespace AircraftCarrier.DrawningObjects
{
public class DrawningAircraftCarrier : DrawningAircraft
{
public DrawningAircraftCarrier(int speed, double weight, Color bodyColor, Color additionalColor, bool cabin, bool runway, int width, int height) :
base(speed, weight, bodyColor, width, height, 164, 40)
{
if (EntityAircraft != null)
{
EntityAircraft = new EntityAircraftCarrier(speed, weight, bodyColor,
additionalColor, cabin, runway);
}
}
public override void DrawTransport(Graphics g)
{
if (EntityAircraft is not EntityAircraftCarrier aircraftCarrie)
{
return;
}
Brush additionalBrush = new SolidBrush(aircraftCarrie.AdditionalColor);
Pen pen = new(Color.White);
if (aircraftCarrie.Cabin)
{
g.FillRectangle(additionalBrush, _startPosX + 4, _startPosY + 13, 59, 14);
g.DrawLine(pen, _startPosX + 62, _startPosY + 19, _startPosX + 52, _startPosY + 19);
g.DrawLine(pen, _startPosX + 47, _startPosY + 19, _startPosX + 37, _startPosY + 19);
g.DrawLine(pen, _startPosX + 32, _startPosY + 19, _startPosX + 22, _startPosY + 19);
g.DrawLine(pen, _startPosX + 17, _startPosY + 19, _startPosX + 7, _startPosY + 19);
}
if (aircraftCarrie.Runway)
{
g.FillRectangle(additionalBrush, _startPosX + 90, _startPosY, 15, 9);
}
base.DrawTransport(g);
}
}
}

View File

@ -1,35 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AircraftCarrier.DrawningObjects;
namespace AircraftCarrier.MovementStrategy
{
public class DrawningObjectAircraft : IMoveableObject
{
private readonly DrawningAircraft? _drawningAircraft = null;
public DrawningObjectAircraft(DrawningAircraft drawningAircraft)
{
_drawningAircraft = drawningAircraft;
}
public ObjectParameters? GetObjectPosition
{
get
{
if (_drawningAircraft == null || _drawningAircraft.EntityAircraft ==
null)
{
return null;
}
return new ObjectParameters(_drawningAircraft.GetPosX,
_drawningAircraft.GetPosY, _drawningAircraft.GetWidth, _drawningAircraft.GetHeight);
}
}
public int GetStep => (int)(_drawningAircraft?.EntityAircraft?.Step ?? 0);
public bool CheckCanMove(Direction direction) =>
_drawningAircraft?.CanMove(direction) ?? false;
public void MoveObject(Direction direction) =>
_drawningAircraft?.MoveTransport(direction);
}
}

View File

@ -1,29 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AircraftCarrier.Entities
{
/// Класс-сущность "Автомобиль"
public class EntityAircraft
{
/// Скорость
public int Speed { get; private set; }
/// Вес
public double Weight { get; private set; }
/// Основной цвет
public Color BodyColor { get; private set; }
public double Step => (double)Speed * 100 / Weight;
/// Конструктор с параметрами
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Основной цвет</param>
public EntityAircraft(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}
}

View File

@ -1,25 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AircraftCarrier.Entities
{
/// Класс-сущность "Спортивный автомобиль"
public class EntityAircraftCarrier : EntityAircraft
{
/// Дополнительный цвет (для опциональных элементов)
public Color AdditionalColor { get; private set; }
/// Признак (опция) наличия кабины
public bool Cabin { get; private set; }
/// Признак (опция) наличия взлетной полосы
public bool Runway { get; private set; }
public double Step => (double)Speed * 100 / Weight;
public EntityAircraftCarrier(int speed, double weight, Color bodyColor, Color additionalColor, bool cabin, bool runway) : base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
Cabin = cabin;
Runway = runway;
}
}
}

View File

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

View File

@ -0,0 +1,10 @@
namespace AircraftCarrier
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}

View File

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

View File

@ -1,180 +0,0 @@
namespace AircraftCarrier
{
partial class FormAircraftCarrier
{
/// <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()
{
pictureBox = new PictureBox();
buttonUp = new Button();
buttonLeft = new Button();
buttonDown = new Button();
buttonRight = new Button();
ButtonCreateAircraftCarrier = new Button();
ButtonCreateAircraft = new Button();
comboBoxStrategy = new ComboBox();
buttonStep = new Button();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
SuspendLayout();
//
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(882, 453);
pictureBox.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBox.TabIndex = 0;
pictureBox.TabStop = false;
pictureBox.Click += buttonMove_Click;
//
// buttonUp
//
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = Properties.Resources.Icon_Up;
buttonUp.BackgroundImageLayout = ImageLayout.Zoom;
buttonUp.Location = new Point(791, 366);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(30, 30);
buttonUp.TabIndex = 2;
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += buttonMove_Click;
//
// buttonLeft
//
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = Properties.Resources.Icon_Left;
buttonLeft.BackgroundImageLayout = ImageLayout.Zoom;
buttonLeft.Location = new Point(755, 402);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(30, 30);
buttonLeft.TabIndex = 3;
buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.Click += buttonMove_Click;
//
// buttonDown
//
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = Properties.Resources.Icon_Down;
buttonDown.BackgroundImageLayout = ImageLayout.Zoom;
buttonDown.Location = new Point(791, 402);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(30, 30);
buttonDown.TabIndex = 4;
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += buttonMove_Click;
//
// buttonRight
//
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = Properties.Resources.Icon_Right;
buttonRight.BackgroundImageLayout = ImageLayout.Zoom;
buttonRight.Location = new Point(827, 402);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(30, 30);
buttonRight.TabIndex = 5;
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += buttonMove_Click;
//
// ButtonCreateAircraftCarrier
//
ButtonCreateAircraftCarrier.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
ButtonCreateAircraftCarrier.Location = new Point(234, 393);
ButtonCreateAircraftCarrier.Name = "ButtonCreateAircraftCarrier";
ButtonCreateAircraftCarrier.Size = new Size(204, 39);
ButtonCreateAircraftCarrier.TabIndex = 6;
ButtonCreateAircraftCarrier.Text = "Создать военный корабль";
ButtonCreateAircraftCarrier.UseVisualStyleBackColor = true;
ButtonCreateAircraftCarrier.Click += ButtonCreateAircraftCarrier_Click;
//
// ButtonCreateAircraft
//
ButtonCreateAircraft.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
ButtonCreateAircraft.Location = new Point(12, 393);
ButtonCreateAircraft.Name = "ButtonCreateAircraft";
ButtonCreateAircraft.Size = new Size(204, 39);
ButtonCreateAircraft.TabIndex = 7;
ButtonCreateAircraft.Text = "Создать корабль";
ButtonCreateAircraft.UseVisualStyleBackColor = true;
ButtonCreateAircraft.Click += ButtonCreateAircraft_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.Anchor = AnchorStyles.Top | AnchorStyles.Right;
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "MoveToCenter", "MoveToBorder" });
comboBoxStrategy.Location = new Point(706, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(151, 28);
comboBoxStrategy.TabIndex = 8;
//
// buttonStep
//
buttonStep.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonStep.Location = new Point(763, 46);
buttonStep.Name = "buttonStep";
buttonStep.Size = new Size(94, 29);
buttonStep.TabIndex = 9;
buttonStep.Text = "Шаг";
buttonStep.UseVisualStyleBackColor = true;
buttonStep.Click += buttonStep_Click;
//
// FormAircraftCarrier
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(882, 453);
Controls.Add(buttonStep);
Controls.Add(comboBoxStrategy);
Controls.Add(ButtonCreateAircraft);
Controls.Add(ButtonCreateAircraftCarrier);
Controls.Add(buttonRight);
Controls.Add(buttonDown);
Controls.Add(buttonLeft);
Controls.Add(buttonUp);
Controls.Add(pictureBox);
Name = "FormAircraftCarrier";
StartPosition = FormStartPosition.CenterScreen;
Text = "AircraftCarrier";
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private PictureBox pictureBox;
private Button buttonUp;
private Button buttonLeft;
private Button buttonDown;
private Button buttonRight;
private Button ButtonCreateAircraft;
private Button ButtonCreateAircraftCarrier;
private ComboBox comboBoxStrategy;
private Button buttonStep;
}
}

View File

@ -1,115 +0,0 @@
using AircraftCarrier.DrawningObjects;
using AircraftCarrier.MovementStrategy;
using System;
namespace AircraftCarrier
{
public partial class FormAircraftCarrier : Form
{
private DrawningAircraft? _drawingAircraft;
private AbstractStrategy? _abstractStrategy;
public FormAircraftCarrier()
{
InitializeComponent();
}
private void Draw()
{
if (_drawingAircraft == null)
{
return;
}
Bitmap bmp = new(pictureBox.Width, pictureBox.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawingAircraft.DrawTransport(gr);
pictureBox.Image = bmp;
}
private void buttonMove_Click(object sender, EventArgs e)
{
if (_drawingAircraft == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
switch (name)
{
case "buttonUp":
_drawingAircraft.MoveTransport(Direction.Up);
break;
case "buttonDown":
_drawingAircraft.MoveTransport(Direction.Down);
break;
case "buttonLeft":
_drawingAircraft.MoveTransport(Direction.Left);
break;
case "buttonRight":
_drawingAircraft.MoveTransport(Direction.Right);
break;
}
Draw();
}
private void ButtonCreateAircraft_Click(object sender, EventArgs e)
{
Random random = new();
_drawingAircraft = new DrawningAircraft(random.Next(100, 300),
random.Next(1000, 3000),
Color.FromArgb(random.Next(0, 256), random.Next(0, 256),
random.Next(0, 256)),
pictureBox.Width, pictureBox.Height);
_drawingAircraft.SetPosition(random.Next(10, 100), random.Next(10,
100));
Draw();
}
private void ButtonCreateAircraftCarrier_Click(object sender, EventArgs e)
{
Random random = new();
_drawingAircraft = new DrawningAircraftCarrier(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)), pictureBox.Width, pictureBox.Height);
_drawingAircraft.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
private void buttonStep_Click(object sender, EventArgs e)
{
if (_drawingAircraft == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_abstractStrategy = comboBoxStrategy.SelectedIndex
switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(new
DrawningObjectAircraft(_drawingAircraft), pictureBox.Width,
pictureBox.Height);
comboBoxStrategy.Enabled = false;
}
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_abstractStrategy = null;
}
}
}
}

View File

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

View File

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

View File

@ -1,55 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AircraftCarrier.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

@ -1,39 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AircraftCarrier.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;
/// Конструктор
/// <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

@ -2,14 +2,16 @@ namespace AircraftCarrier
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormAircraftCarrier());
Application.Run(new Form1());
}
}
}

View File

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

View File

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

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 KiB

View File

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