Compare commits

...

17 Commits

Author SHA1 Message Date
7310407399 Merge pull request 'Tsukanova I.V. LabWork4' (#5) from LabWork04 into LabWork03
Reviewed-on: http://student.git.athene.tech/Senju/PIbd-22_Tsukanova_I.V._AircraftCarrier_Base/pulls/5
2022-10-21 09:35:27 +04:00
49727eceb0 Этап 3. Форма 2022-10-15 21:12:39 +04:00
5efdfaea7a Этап 2. Класс MapColection 2022-10-15 19:08:56 +04:00
ba6554f76a Этап 1. Смена массива на список 2022-10-15 18:59:41 +04:00
e8e0bd9329 Внесла некоторые изменения 2022-10-04 23:32:55 +04:00
4b867003e2 Немного доработанная форма 2022-10-01 12:51:41 +04:00
d19cbf92bb Changes forms 2022-10-01 12:18:31 +04:00
068933cb5b Generic classes 2022-10-01 09:52:43 +04:00
c3b6d7169e Полностью готовая 2022-09-30 19:41:15 +04:00
9a8bafa283 Полностью готовая вторая лабораторная 2022-09-21 10:52:37 +04:00
711b7d213b Добавлена вторая карта 2022-09-21 10:06:30 +04:00
128e854feb Абстрактный класс 2022-09-21 00:36:21 +04:00
8b1391adee Добавление интерфейса 2022-09-20 23:42:48 +04:00
098ef0c921 Продвинутый объект 2022-09-20 23:20:22 +04:00
01cffb5f90 Добавлен класс DrawingAircraftCarrier 2022-09-20 18:26:55 +04:00
7f1f1ca3e4 Добавлен класс DrawingAircraftCarrier 2022-09-18 21:41:23 +04:00
629f4919c0 Переход на конструкторы 2022-09-17 11:17:47 +04:00
19 changed files with 1586 additions and 74 deletions

View File

@ -0,0 +1,160 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AircraftCarrier
{
internal abstract class AbstractMap
{
private IDrawingObject _drawingObject = null;
protected int[,] _map = null;
protected int _width;
protected int _height;
protected float _size_x;
protected float _size_y;
protected readonly Random _random = new();
protected readonly int _freeRoad = 0;
protected readonly int _barrier = 1;
public Bitmap CreateMap(int width, int height, IDrawingObject drawningObject)
{
_width = width;
_height = height;
_drawingObject = drawningObject;
GenerateMap();
while (!SetObjectOnMap())
{
GenerateMap();
}
return DrawMapWithObject();
}
public Bitmap MoveObject(Direction direction)
{
if (_drawingObject != null)
{
if (true)
{
_drawingObject.MoveObject(direction);
}
(float Left, float Right, float Top, float Bottom) = _drawingObject.GetCurrentPosition();
if (Check(Left, Right, Top, Bottom) != 0)
{
_drawingObject.MoveObject(GetOpositDirection(direction));
}
return DrawMapWithObject();
}
return null;
}
private Direction GetOpositDirection(Direction dir)
{
switch (dir)
{
case Direction.None:
return Direction.None;
case Direction.Up:
return Direction.Down;
case Direction.Down:
return Direction.Up;
case Direction.Left:
return Direction.Right;
case Direction.Right:
return Direction.Left;
}
return Direction.None;
}
private bool SetObjectOnMap()
{
if (_drawingObject == null || _map == null)
{
return false;
}
int x = _random.Next(0, 10);
int y = _random.Next(0, 10);
_drawingObject.SetObject(x, y, _width, _height);
(float Left, float Right, float Top, float Bottom) = _drawingObject.GetCurrentPosition();
float nowX = Left;
float nowY = Right;
float lenX = Top - Left;
float lenY = Bottom - Right;
while (Check(nowX, nowY, nowX + lenX, nowY + lenY) != 2)
{
int result;
do
{
result = Check(nowX, nowY, nowX + lenX, nowY + lenY);
if (result == 0)
{
_drawingObject.SetObject((int)nowX, (int)nowY, _width, _height);
return true;
}
else
{
nowX += _size_x;
}
} while (result != 2);
nowX = x;
nowY += _size_y;
}
return false;
}
private int Check(float Left, float Right, float Top, float Bottom)
{
int startX = (int)(Left / _size_x);
int startY = (int)(Right / _size_y);
int endX = (int)(Top / _size_x);
int endY = (int)(Bottom / _size_y);
if (startX < 0 || startY < 0 || endX >= _map.GetLength(0) || endY >= _map.GetLength(0))
{
return 2;
}
for (int i = startX; i <= endX; i++)
{
for (int j = startY; j <= endY; j++)
{
if (_map[i, j] == _barrier)
{
return 1;
}
}
}
return 0;
}
private Bitmap DrawMapWithObject()
{
Bitmap bmp = new(_width, _height);
if (_drawingObject == null || _map == null)
{
return bmp;
}
Graphics gr = Graphics.FromImage(bmp);
for (int i = 0; i < _map.GetLength(0); ++i)
{
for (int j = 0; j < _map.GetLength(1); ++j)
{
if (_map[i, j] == _freeRoad)
{
DrawRoadPart(gr, i, j);
}
else if (_map[i, j] == _barrier)
{
DrawBarrierPart(gr, i, j);
}
}
}
_drawingObject.DrawningObject(gr);
return bmp;
}
protected abstract void GenerateMap();
protected abstract void DrawRoadPart(Graphics g, int i, int j);
protected abstract void DrawBarrierPart(Graphics g, int i, int j);
}
}

View File

@ -9,8 +9,9 @@ namespace AircraftCarrier
/// <summary>
/// Направление перемещения
/// </summary>
internal enum Direction
public enum Direction
{
None = 0,
Up = 1,
Down = 2,
Left = 3,

View File

@ -0,0 +1,100 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AircraftCarrier
{
internal class DrawingAircraftCarrier : DrawingWarship
{
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес военного корабля</param>
/// <param name="bodyColor">Цвет основной палубы</param>
/// <param name="dopColor">Дополнительный цвет</param>
/// <param name="bodyKit">Признак наличия боковой площадки</param>
/// <param name="сabin">Признак наличия рубки</param>
/// <param name="superEngine">Признак наличия усиленного двигателя</param>
public DrawingAircraftCarrier(int speed, float weight, Color bodyColor, Color dopColor, bool bodyKit, bool сabin, bool superEngine) :
base(speed, weight, bodyColor, 114, 40)
{
Warship = new EntityAircraftCarrier(speed, weight, bodyColor, dopColor, bodyKit, сabin, superEngine);
}
public override void DrawTransport(Graphics g)
{
if(Warship is not EntityAircraftCarrier aircraftCarrier)
{
return;
}
Pen pen = new(Color.Black);
Brush dopBrush = new SolidBrush(aircraftCarrier.DopColor);
Brush brGray = new SolidBrush(Color.Gray);
Brush brRed = new SolidBrush(Color.Red);
Brush br = new SolidBrush(Warship?.BodyColor ?? Color.White);
if (aircraftCarrier.BodyKit)
{
//боковая площадка
PointF pointAircraftCarrier1 = new PointF(_startPosX + 94, _startPosY + 40);
PointF pointAircraftCarrier2 = new PointF(_startPosX + 74, _startPosY + 60);
PointF pointAircraftCarrier3 = new PointF(_startPosX + 24, _startPosY + 60);
PointF pointAircraftCarrier4 = new PointF(_startPosX + 4, _startPosY + 40);
PointF[] PointsAircraftCarrier =
{
pointAircraftCarrier1, pointAircraftCarrier2, pointAircraftCarrier3, pointAircraftCarrier4
};
g.FillPolygon(br, PointsAircraftCarrier);
g.DrawPolygon(pen, PointsAircraftCarrier);
//полоса
PointF pontStartLine1 = new PointF(_startPosX + 4, _startPosY);
PointF pontStartLine2 = new PointF(_startPosX + 15, _startPosY);
PointF pontStartLine3 = new PointF(_startPosX + 74, _startPosY + 60);
PointF pontStartLine4 = new PointF(_startPosX + 59, _startPosY + 60);
PointF[] PointsStartLine =
{
pontStartLine1, pontStartLine2, pontStartLine3, pontStartLine4
};
g.FillPolygon(brGray, PointsStartLine);
g.DrawPolygon(pen, PointsStartLine);
}
if (aircraftCarrier.SuperEngine)
{
g.FillEllipse(brRed, _startPosX, _startPosY, 10, 10);
g.DrawEllipse(pen, _startPosX, _startPosY, 10, 10);
g.FillEllipse(brRed, _startPosX, _startPosY + 10, 10, 10);
g.DrawEllipse(pen, _startPosX, _startPosY + 10, 10, 10);
g.FillEllipse(brRed, _startPosX, _startPosY + 18, 10, 10);
g.DrawEllipse(pen, _startPosX, _startPosY + 18, 10, 10);
g.FillEllipse(brRed, _startPosX, _startPosY + 30, 10, 10);
g.DrawEllipse(pen, _startPosX, _startPosY + 30, 10, 10);
}
base.DrawTransport(g);
if (aircraftCarrier.Сabin)
{
g.FillEllipse(brGray, _startPosX + 10, _startPosY + 15, 10, 10);
g.DrawEllipse(pen, _startPosX + 10, _startPosY + 15, 10, 10);
g.FillEllipse(brGray, _startPosX + 20, _startPosY + 15, 10, 10);
g.DrawEllipse(pen, _startPosX + 20, _startPosY + 15, 10, 10);
g.FillRectangle(brGray, _startPosX + 15, _startPosY + 15, 10, 10);
g.DrawRectangle(pen, _startPosX + 15, _startPosY + 15, 10, 10);
}
}
}
}

View File

@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AircraftCarrier
{
internal class DrawingObjectWarship : IDrawingObject
{
private DrawingWarship _warship = null;
public DrawingObjectWarship(DrawingWarship warship)
{
_warship = warship;
}
public float Step => _warship?.Warship?.Step ?? 0;
public (float Left, float Right, float Top, float Bottom) GetCurrentPosition()
{
return _warship?.GetCurrentPosition() ?? default;
}
public void MoveObject(Direction direction)
{
_warship?.MoveTransport(direction);
}
public void SetObject(int x, int y, int width, int height)
{
_warship.SetPosition(x, y, width, height);
}
void IDrawingObject.DrawningObject(Graphics g)
{
_warship.DrawTransport(g);
}
}
}

View File

@ -9,20 +9,20 @@ namespace AircraftCarrier
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
internal class DrawingWarship
public class DrawingWarship
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityWarship Warship { get; private set; }
public EntityWarship Warship { get; protected set; }
/// <summary>
/// Левая координата отрисовки военного корабля
/// </summary>
private float _startPosX;
protected float _startPosX;
/// <summary>
/// Верхняя кооридната отрисовки военного корабля
/// </summary>
private float _startPosY;
protected float _startPosY;
/// <summary>
/// Ширина окна отрисовки
/// </summary>
@ -34,7 +34,7 @@ namespace AircraftCarrier
/// <summary>
/// Ширина отрисовки военного корабля
/// </summary>
private readonly int _warshipWidth = 94;
private readonly int _warshipWidth = 114;
/// <summary>
/// Высота отрисовки военного корабля
/// </summary>
@ -45,10 +45,24 @@ namespace AircraftCarrier
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес военного корабля</param>
/// <param name="bodyColor">Цвет главной палубы</param>
public void Init(int speed, float weight, Color bodyColor)
public DrawingWarship(int speed, float weight, Color bodyColor)
{
Warship = new EntityWarship();
Warship.Init(speed, weight, bodyColor);
Warship = new EntityWarship(speed, weight, bodyColor);
}
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес военного корабля</param>
/// <param name="bodyColor">Цвет главной палубы</param>
/// <param name="carWidth">Ширина отрисовки автомобиля</param>
/// <param name="carHeight">Высота отрисовки автомобиля</param>
protected DrawingWarship(int speed, float weight, Color bodyColor, int warshipWidth, int warshipHeight) :
this(speed, weight, bodyColor)
{
_warshipWidth = warshipWidth;
_warshipHeight = warshipHeight;
}
/// <summary>
/// Установка позиции военного корабля
@ -58,28 +72,15 @@ namespace AircraftCarrier
/// <param name="width"></param>
/// <param name="height"></param>
public void SetPosition(int x, int y, int width, int height)
{
if (width >= x + _warshipWidth && height >= y + _warshipHeight && x >= 0 && y >= 0)
{
_startPosX = x;
_startPosY = y;
_pictureWidth = width;
_pictureHeight = height;
if (width < _warshipWidth)
{
width = _warshipWidth;
}
if (height < _warshipHeight)
{
height = _warshipHeight;
}
if(x + _warshipWidth > width)
{
_startPosX -= x + _warshipWidth - width;
}
if (y + _warshipHeight > height)
{
_pictureHeight -= y + _warshipHeight - height;
}
else return;
}
/// <summary>
/// Изменение направления пермещения
@ -102,14 +103,14 @@ namespace AircraftCarrier
break;
//влево
case Direction.Left:
if(_startPosX - Warship.Step > 0)
if(_startPosX - Warship.Step >= 0)
{
_startPosX -= Warship.Step;
}
break;
//вверх
case Direction.Up:
if (_startPosY - Warship.Step > 0)
if (_startPosY - Warship.Step >= 0)
{
_startPosY -= Warship.Step;
}
@ -128,7 +129,7 @@ namespace AircraftCarrier
/// Отрисовка военного корабля
/// </summary>
/// <param name="g"></param>
public void DrawTransport(Graphics g)
public virtual void DrawTransport(Graphics g)
{
if (_startPosX < 0 || _startPosY < 0
|| !_pictureHeight.HasValue || !_pictureWidth.HasValue)
@ -136,38 +137,37 @@ namespace AircraftCarrier
return;
}
Pen pen = new(Color.Black);
//границы военного корабля
PointF point1 = new PointF(_startPosX, _startPosY);
PointF point2 = new PointF(_startPosX + 74, _startPosY);
PointF point3 = new PointF(_startPosX + 94, _startPosY + 20);
PointF point4 = new PointF(_startPosX + 74, _startPosY + 40);
PointF point5 = new PointF(_startPosX, _startPosY + 40);
PointF[] curvePoints =
{
point1, point2, point3, point4, point5
};
g.DrawPolygon(pen, curvePoints);
Brush brOrange = new SolidBrush(Color.Orange);
Brush brPurple = new SolidBrush(Color.RebeccaPurple);
//главная палуба
Brush br = new SolidBrush(Warship?.BodyColor ?? Color.White);
g.FillPolygon(br, curvePoints);
PointF pointWarship1 = new PointF(_startPosX + 4, _startPosY);
PointF pointWarship2 = new PointF(_startPosX + 94, _startPosY);
PointF pointWarship3 = new PointF(_startPosX + 114, _startPosY + 20);
PointF pointWarship4 = new PointF(_startPosX + 94, _startPosY + 40);
PointF pointWarship5 = new PointF(_startPosX + 4, _startPosY + 40);
PointF[] PointsWarship =
{
pointWarship1, pointWarship2, pointWarship3, pointWarship4, pointWarship5
};
g.FillPolygon(br, PointsWarship);
g.DrawPolygon(pen, PointsWarship);
//мачта
Brush brWhite = new SolidBrush(Color.White);
g.FillEllipse(brWhite, _startPosX + 59, _startPosY + 13, 15, 15);
g.FillEllipse(brOrange, _startPosX + 79, _startPosY + 13, 15, 15);
//границы мачты
g.DrawEllipse(pen, _startPosX + 59, _startPosY + 13, 15, 15);
g.DrawEllipse(pen, _startPosX + 79, _startPosY + 13, 15, 15);
//палуба
g.FillRectangle(brWhite, _startPosX + 44, _startPosY + 10, 10, 20);
g.FillRectangle(brWhite, _startPosX + 24, _startPosY + 15, 20, 10);
g.FillRectangle(brPurple, _startPosX + 64, _startPosY + 10, 10, 20);
g.FillRectangle(brPurple, _startPosX + 44, _startPosY + 15, 20, 10);
//границы палуба
g.DrawRectangle(pen, _startPosX + 44, _startPosY + 10, 10, 20);
g.DrawRectangle(pen, _startPosX + 24, _startPosY + 15, 20, 10);
g.DrawRectangle(pen, _startPosX + 64, _startPosY + 10, 10, 20);
g.DrawRectangle(pen, _startPosX + 44, _startPosY + 15, 20, 10);
//двигатели
Brush brBlack = new SolidBrush(Color.Black);
@ -199,6 +199,13 @@ namespace AircraftCarrier
_startPosY = _pictureHeight.Value - _warshipHeight;
}
}
/// <summary>
/// Получение текущей позиции объекта
/// </summary>
/// <returns></returns>
public (float Left, float Right, float Top, float Bottom) GetCurrentPosition()
{
return (_startPosX, _startPosY, _startPosX + _warshipWidth, _startPosY + _warshipHeight);
}
}
}

View File

@ -0,0 +1,46 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AircraftCarrier
{
internal class EntityAircraftCarrier : EntityWarship
{
/// <summary>
/// Дополнительный цвет
/// </summary>
public Color DopColor { get; private set; }
/// <summary>
/// Признак наличия боковой площадки
/// </summary>
public bool BodyKit { get; private set; }
/// <summary>
/// Признак наличия рубки
/// </summary>
public bool Сabin { get; private set; }
/// <summary>
/// Признак наличия усиленного двигателя
/// </summary>
public bool SuperEngine { get; private set; }
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес военного корабля</param>
/// <param name="bodyColor">Цвет основной палубы</param>
/// <param name="dopColor">Дополнительный цвет</param>
/// <param name="bodyKit">Признак наличия боковой площадки</param>
/// <param name="сabin">Признак наличия рубки</param>
/// <param name="superEngine">Признак наличия усиленного двигателя</param>
public EntityAircraftCarrier(int speed, float weight, Color bodyColor, Color dopColor, bool bodyKit, bool сabin, bool superEngine) :
base(speed, weight, bodyColor)
{
DopColor = dopColor;
BodyKit = bodyKit;
Сabin = сabin;
SuperEngine = superEngine;
}
}
}

View File

@ -9,7 +9,7 @@ namespace AircraftCarrier
/// <summary>
/// Класс - сущность "Военный корабль"
/// </summary>
internal class EntityWarship
public class EntityWarship
{
/// <summary>
/// Скорость
@ -33,14 +33,12 @@ namespace AircraftCarrier
/// <param name="speed"></param>
/// <param name="weight"></param>
/// <param name="bodyColor"></param>
public void Init(int speed, float weight, Color bodyColor)
public EntityWarship(int speed, float weight, Color bodyColor)
{
Random rnd = new();
Speed = speed <= 0 ? rnd.Next(50, 150) : speed;
Weight = weight <= 0 ? rnd.Next(40, 70) : weight;
BodyColor = bodyColor;
}
}
}

View File

@ -0,0 +1,284 @@
namespace AircraftCarrier
{
partial class FormMapWithSetWarships
{
/// <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.groupBoxTools = new System.Windows.Forms.GroupBox();
this.groupBoxMaps = new System.Windows.Forms.GroupBox();
this.buttonAddMap = new System.Windows.Forms.Button();
this.buttonDeleteMap = new System.Windows.Forms.Button();
this.listBoxMaps = new System.Windows.Forms.ListBox();
this.textBoxNewMapName = new System.Windows.Forms.TextBox();
this.comboBoxSelectorMap = new System.Windows.Forms.ComboBox();
this.buttonShowOnMap = new System.Windows.Forms.Button();
this.buttonShowStorage = new System.Windows.Forms.Button();
this.buttonRemoveWarship = new System.Windows.Forms.Button();
this.maskedTextBoxPosition = new System.Windows.Forms.MaskedTextBox();
this.buttonAddWarship = new System.Windows.Forms.Button();
this.buttonRight = new System.Windows.Forms.Button();
this.buttonLeft = new System.Windows.Forms.Button();
this.buttonUp = new System.Windows.Forms.Button();
this.buttonDown = new System.Windows.Forms.Button();
this.pictureBox = new System.Windows.Forms.PictureBox();
this.groupBoxTools.SuspendLayout();
this.groupBoxMaps.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
this.SuspendLayout();
//
// groupBoxTools
//
this.groupBoxTools.Controls.Add(this.groupBoxMaps);
this.groupBoxTools.Controls.Add(this.buttonShowOnMap);
this.groupBoxTools.Controls.Add(this.buttonShowStorage);
this.groupBoxTools.Controls.Add(this.buttonRemoveWarship);
this.groupBoxTools.Controls.Add(this.maskedTextBoxPosition);
this.groupBoxTools.Controls.Add(this.buttonAddWarship);
this.groupBoxTools.Controls.Add(this.buttonRight);
this.groupBoxTools.Controls.Add(this.buttonLeft);
this.groupBoxTools.Controls.Add(this.buttonUp);
this.groupBoxTools.Controls.Add(this.buttonDown);
this.groupBoxTools.Dock = System.Windows.Forms.DockStyle.Right;
this.groupBoxTools.Location = new System.Drawing.Point(754, 0);
this.groupBoxTools.Name = "groupBoxTools";
this.groupBoxTools.Size = new System.Drawing.Size(217, 649);
this.groupBoxTools.TabIndex = 0;
this.groupBoxTools.TabStop = false;
this.groupBoxTools.Text = "Tools";
//
// groupBoxMaps
//
this.groupBoxMaps.Controls.Add(this.buttonAddMap);
this.groupBoxMaps.Controls.Add(this.buttonDeleteMap);
this.groupBoxMaps.Controls.Add(this.listBoxMaps);
this.groupBoxMaps.Controls.Add(this.textBoxNewMapName);
this.groupBoxMaps.Controls.Add(this.comboBoxSelectorMap);
this.groupBoxMaps.Location = new System.Drawing.Point(6, 22);
this.groupBoxMaps.Name = "groupBoxMaps";
this.groupBoxMaps.Size = new System.Drawing.Size(205, 257);
this.groupBoxMaps.TabIndex = 19;
this.groupBoxMaps.TabStop = false;
this.groupBoxMaps.Text = "Maps";
//
// buttonAddMap
//
this.buttonAddMap.Location = new System.Drawing.Point(14, 80);
this.buttonAddMap.Name = "buttonAddMap";
this.buttonAddMap.Size = new System.Drawing.Size(180, 35);
this.buttonAddMap.TabIndex = 2;
this.buttonAddMap.Text = "Add map";
this.buttonAddMap.UseVisualStyleBackColor = true;
this.buttonAddMap.Click += new System.EventHandler(this.ButtonAddMap_Click);
//
// buttonDeleteMap
//
this.buttonDeleteMap.Location = new System.Drawing.Point(14, 206);
this.buttonDeleteMap.Name = "buttonDeleteMap";
this.buttonDeleteMap.Size = new System.Drawing.Size(180, 35);
this.buttonDeleteMap.TabIndex = 4;
this.buttonDeleteMap.Text = "Delete map";
this.buttonDeleteMap.UseVisualStyleBackColor = true;
this.buttonDeleteMap.Click += new System.EventHandler(this.ButtonDeleteMap_Click);
//
// listBoxMaps
//
this.listBoxMaps.FormattingEnabled = true;
this.listBoxMaps.ItemHeight = 15;
this.listBoxMaps.Location = new System.Drawing.Point(14, 121);
this.listBoxMaps.Name = "listBoxMaps";
this.listBoxMaps.Size = new System.Drawing.Size(180, 79);
this.listBoxMaps.TabIndex = 3;
this.listBoxMaps.SelectedIndexChanged += new System.EventHandler(this.ListBoxMaps_SelectedIndexChanged);
//
// textBoxNewMapName
//
this.textBoxNewMapName.Location = new System.Drawing.Point(14, 22);
this.textBoxNewMapName.Name = "textBoxNewMapName";
this.textBoxNewMapName.Size = new System.Drawing.Size(180, 23);
this.textBoxNewMapName.TabIndex = 0;
//
// comboBoxSelectorMap
//
this.comboBoxSelectorMap.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxSelectorMap.FormattingEnabled = true;
this.comboBoxSelectorMap.Items.AddRange(new object[] {
"Простая карта",
"Преграды-линии"});
this.comboBoxSelectorMap.Location = new System.Drawing.Point(14, 51);
this.comboBoxSelectorMap.Name = "comboBoxSelectorMap";
this.comboBoxSelectorMap.Size = new System.Drawing.Size(180, 23);
this.comboBoxSelectorMap.TabIndex = 9;
//
// buttonShowOnMap
//
this.buttonShowOnMap.Location = new System.Drawing.Point(20, 516);
this.buttonShowOnMap.Name = "buttonShowOnMap";
this.buttonShowOnMap.Size = new System.Drawing.Size(180, 35);
this.buttonShowOnMap.TabIndex = 18;
this.buttonShowOnMap.Text = "Show map";
this.buttonShowOnMap.UseVisualStyleBackColor = true;
this.buttonShowOnMap.Click += new System.EventHandler(this.ButtonShowOnMap_Click);
//
// buttonShowStorage
//
this.buttonShowStorage.Location = new System.Drawing.Point(20, 475);
this.buttonShowStorage.Name = "buttonShowStorage";
this.buttonShowStorage.Size = new System.Drawing.Size(180, 35);
this.buttonShowStorage.TabIndex = 17;
this.buttonShowStorage.Text = "Show storage";
this.buttonShowStorage.UseVisualStyleBackColor = true;
this.buttonShowStorage.Click += new System.EventHandler(this.ButtonShowStorage_Click);
//
// buttonRemoveWarship
//
this.buttonRemoveWarship.Location = new System.Drawing.Point(20, 434);
this.buttonRemoveWarship.Name = "buttonRemoveWarship";
this.buttonRemoveWarship.Size = new System.Drawing.Size(180, 35);
this.buttonRemoveWarship.TabIndex = 16;
this.buttonRemoveWarship.Text = "Remove warship";
this.buttonRemoveWarship.UseVisualStyleBackColor = true;
this.buttonRemoveWarship.Click += new System.EventHandler(this.ButtonRemoveWarship_Click);
//
// maskedTextBoxPosition
//
this.maskedTextBoxPosition.Location = new System.Drawing.Point(20, 405);
this.maskedTextBoxPosition.Mask = "00";
this.maskedTextBoxPosition.Name = "maskedTextBoxPosition";
this.maskedTextBoxPosition.Size = new System.Drawing.Size(180, 23);
this.maskedTextBoxPosition.TabIndex = 15;
this.maskedTextBoxPosition.ValidatingType = typeof(int);
//
// buttonAddWarship
//
this.buttonAddWarship.Location = new System.Drawing.Point(20, 364);
this.buttonAddWarship.Name = "buttonAddWarship";
this.buttonAddWarship.Size = new System.Drawing.Size(180, 35);
this.buttonAddWarship.TabIndex = 14;
this.buttonAddWarship.Text = "Add warship";
this.buttonAddWarship.UseVisualStyleBackColor = true;
this.buttonAddWarship.Click += new System.EventHandler(this.ButtonAddWarship_Click);
//
// buttonRight
//
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::AircraftCarrier.Properties.Resources.ArrowRight;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonRight.Location = new System.Drawing.Point(126, 609);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(30, 30);
this.buttonRight.TabIndex = 13;
this.buttonRight.Text = " ";
this.buttonRight.UseVisualStyleBackColor = true;
this.buttonRight.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonLeft
//
this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonLeft.BackgroundImage = global::AircraftCarrier.Properties.Resources.ArrowLeft;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonLeft.Location = new System.Drawing.Point(54, 609);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(30, 30);
this.buttonLeft.TabIndex = 12;
this.buttonLeft.Text = " ";
this.buttonLeft.UseVisualStyleBackColor = true;
this.buttonLeft.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonUp
//
this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonUp.BackgroundImage = global::AircraftCarrier.Properties.Resources.ArrowUp;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonUp.Location = new System.Drawing.Point(90, 573);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(30, 30);
this.buttonUp.TabIndex = 11;
this.buttonUp.Text = " ";
this.buttonUp.UseVisualStyleBackColor = true;
this.buttonUp.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonDown
//
this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDown.BackgroundImage = global::AircraftCarrier.Properties.Resources.ArrowDown;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonDown.Location = new System.Drawing.Point(90, 609);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(30, 30);
this.buttonDown.TabIndex = 10;
this.buttonDown.Text = " ";
this.buttonDown.UseVisualStyleBackColor = true;
this.buttonDown.Click += new System.EventHandler(this.ButtonMove_Click);
//
// pictureBox
//
this.pictureBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBox.Location = new System.Drawing.Point(0, 0);
this.pictureBox.Name = "pictureBox";
this.pictureBox.Size = new System.Drawing.Size(754, 649);
this.pictureBox.TabIndex = 1;
this.pictureBox.TabStop = false;
//
// FormMapWithSetWarships
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(971, 649);
this.Controls.Add(this.pictureBox);
this.Controls.Add(this.groupBoxTools);
this.Name = "FormMapWithSetWarships";
this.Text = "FormMapWithSetWarships";
this.groupBoxTools.ResumeLayout(false);
this.groupBoxTools.PerformLayout();
this.groupBoxMaps.ResumeLayout(false);
this.groupBoxMaps.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
this.ResumeLayout(false);
}
#endregion
private GroupBox groupBoxTools;
private PictureBox pictureBox;
private ComboBox comboBoxSelectorMap;
private Button buttonRight;
private Button buttonLeft;
private Button buttonUp;
private Button buttonDown;
private Button buttonShowOnMap;
private Button buttonShowStorage;
private Button buttonRemoveWarship;
private MaskedTextBox maskedTextBoxPosition;
private Button buttonAddWarship;
private GroupBox groupBoxMaps;
private Button buttonAddMap;
private Button buttonDeleteMap;
private ListBox listBoxMaps;
private TextBox textBoxNewMapName;
}
}

View File

@ -0,0 +1,224 @@
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 static System.Windows.Forms.DataFormats;
namespace AircraftCarrier
{
public partial class FormMapWithSetWarships : Form
{
/// <summary>
/// Словарь для выпадающего списка
/// </summary>
private readonly Dictionary<string, AbstractMap> _mapsDict = new()
{
{ "Простая карта", new SimpleMap() },
{ "Преграды-линии", new LineMap() }
};
/// <summary>
/// Объект от коллекции карт
/// </summary>
private readonly MapsCollection _mapsCollection;
/// <summary>
/// Конструктор
/// </summary>
public FormMapWithSetWarships()
{
InitializeComponent();
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
comboBoxSelectorMap.Items.Clear();
foreach (var elem in _mapsDict)
{
comboBoxSelectorMap.Items.Add(elem.Key);
}
}
/// <summary>
/// Заполнение listBoxMaps
/// </summary>
private void ReloadMaps()
{
int index = listBoxMaps.SelectedIndex;
listBoxMaps.Items.Clear();
for (int i = 0; i < _mapsCollection.Keys.Count; i++)
{
listBoxMaps.Items.Add(_mapsCollection.Keys[i]);
}
if (listBoxMaps.Items.Count > 0 && (index == -1 || index >= listBoxMaps.Items.Count))
{
listBoxMaps.SelectedIndex = 0;
}
else if (listBoxMaps.Items.Count > 0 && index > -1 && index < listBoxMaps.Items.Count)
{
listBoxMaps.SelectedIndex = index;
}
}
/// <summary>
/// Добавление карты
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddMap_Click(object sender, EventArgs e)
{
if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (!_mapsDict.ContainsKey(comboBoxSelectorMap.Text))
{
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps();
}
/// <summary>
/// Выбор карты
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
/// <summary>
/// Удаление карты
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonDeleteMap_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps();
}
}
/// <summary>
/// Добавление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddWarship_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
FormWarship form = new();
if (form.ShowDialog() == DialogResult.OK)
{
DrawingObjectWarship warship = new(form.SelectedWarship);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + warship >= 0)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
}
/// <summary>
/// Удаление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveWarship_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text))
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
/// <summary>
/// Вывод набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonShowStorage_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
/// <summary>
/// Вывод карты
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonShowOnMap_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowOnMap();
}
/// <summary>
/// Перемещение
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
//получаем имя кнопки
string name = ((Button)sender)?.Name ?? string.Empty;
Direction dir = Direction.None;
switch (name)
{
case "buttonUp":
dir = Direction.Up;
break;
case "buttonDown":
dir = Direction.Down;
break;
case "buttonLeft":
dir = Direction.Left;
break;
case "buttonRight":
dir = Direction.Right;
break;
}
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].MoveObject(dir);
}
}
}

View File

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

View File

@ -38,6 +38,8 @@
this.buttonUp = new System.Windows.Forms.Button();
this.buttonLeft = new System.Windows.Forms.Button();
this.buttonRight = new System.Windows.Forms.Button();
this.buttonCreateModif = new System.Windows.Forms.Button();
this.buttonSelectWarship = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxWarship)).BeginInit();
this.statusStrip.SuspendLayout();
this.SuspendLayout();
@ -47,7 +49,7 @@
this.pictureBoxWarship.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBoxWarship.Location = new System.Drawing.Point(0, 0);
this.pictureBoxWarship.Name = "pictureBoxWarship";
this.pictureBoxWarship.Size = new System.Drawing.Size(510, 426);
this.pictureBoxWarship.Size = new System.Drawing.Size(768, 426);
this.pictureBoxWarship.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pictureBoxWarship.TabIndex = 0;
this.pictureBoxWarship.TabStop = false;
@ -61,7 +63,7 @@
this.toolStripStatusLabelBodyColor});
this.statusStrip.Location = new System.Drawing.Point(0, 426);
this.statusStrip.Name = "statusStrip";
this.statusStrip.Size = new System.Drawing.Size(510, 22);
this.statusStrip.Size = new System.Drawing.Size(768, 22);
this.statusStrip.TabIndex = 1;
//
// toolStripStatusLabelSpeed
@ -98,7 +100,7 @@
this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDown.BackgroundImage = global::AircraftCarrier.Properties.Resources.ArrowDown;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonDown.Location = new System.Drawing.Point(428, 386);
this.buttonDown.Location = new System.Drawing.Point(686, 386);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(30, 30);
this.buttonDown.TabIndex = 3;
@ -111,7 +113,7 @@
this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonUp.BackgroundImage = global::AircraftCarrier.Properties.Resources.ArrowUp;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonUp.Location = new System.Drawing.Point(428, 350);
this.buttonUp.Location = new System.Drawing.Point(686, 350);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(30, 30);
this.buttonUp.TabIndex = 4;
@ -124,7 +126,7 @@
this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonLeft.BackgroundImage = global::AircraftCarrier.Properties.Resources.ArrowLeft;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonLeft.Location = new System.Drawing.Point(392, 386);
this.buttonLeft.Location = new System.Drawing.Point(650, 386);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(30, 30);
this.buttonLeft.TabIndex = 5;
@ -137,7 +139,7 @@
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::AircraftCarrier.Properties.Resources.ArrowRight;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonRight.Location = new System.Drawing.Point(464, 386);
this.buttonRight.Location = new System.Drawing.Point(722, 386);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(30, 30);
this.buttonRight.TabIndex = 6;
@ -145,11 +147,33 @@
this.buttonRight.UseVisualStyleBackColor = true;
this.buttonRight.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonCreateModif
//
this.buttonCreateModif.Location = new System.Drawing.Point(93, 393);
this.buttonCreateModif.Name = "buttonCreateModif";
this.buttonCreateModif.Size = new System.Drawing.Size(92, 23);
this.buttonCreateModif.TabIndex = 7;
this.buttonCreateModif.Text = "Modification";
this.buttonCreateModif.UseVisualStyleBackColor = true;
this.buttonCreateModif.Click += new System.EventHandler(this.ButtonCreateModif_Click);
//
// buttonSelectWarship
//
this.buttonSelectWarship.Location = new System.Drawing.Point(530, 393);
this.buttonSelectWarship.Name = "buttonSelectWarship";
this.buttonSelectWarship.Size = new System.Drawing.Size(75, 23);
this.buttonSelectWarship.TabIndex = 8;
this.buttonSelectWarship.Text = "Select";
this.buttonSelectWarship.UseVisualStyleBackColor = true;
this.buttonSelectWarship.Click += new System.EventHandler(this.ButtonSelectWarship_Click);
//
// FormWarship
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(510, 448);
this.ClientSize = new System.Drawing.Size(768, 448);
this.Controls.Add(this.buttonSelectWarship);
this.Controls.Add(this.buttonCreateModif);
this.Controls.Add(this.buttonRight);
this.Controls.Add(this.buttonLeft);
this.Controls.Add(this.buttonUp);
@ -179,5 +203,7 @@
private Button buttonUp;
private Button buttonLeft;
private Button buttonRight;
private Button buttonCreateModif;
private Button buttonSelectWarship;
}
}

View File

@ -3,6 +3,10 @@ namespace AircraftCarrier
public partial class FormWarship : Form
{
private DrawingWarship _warship;
/// <summary>
/// Âûáðàííûé îáúåêò
/// </summary>
public DrawingWarship SelectedWarship { get; private set; }
public FormWarship()
{
InitializeComponent();
@ -18,6 +22,17 @@ namespace AircraftCarrier
pictureBoxWarship.Image = bmp;
}
/// <summary>
/// Ìåòîä óñòàíîâêè äàííûõ
/// </summary>
private void SetData()
{
Random rnd = new();
_warship.SetPosition(rnd.Next(10, 100), rnd.Next(10, 100), pictureBoxWarship.Width, pictureBoxWarship.Height);
toolStripStatusLabelSpeed.Text = $"Ñêîðîñòü: {_warship.Warship.Speed}";
toolStripStatusLabelWeight.Text = $"Âåñ: {_warship.Warship.Weight}";
toolStripStatusLabelBodyColor.Text = $"Öâåò: {_warship.Warship.BodyColor.Name}";
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Create"
/// </summary>
/// <param name="sender"></param>
@ -25,15 +40,21 @@ namespace AircraftCarrier
private void ButtonCreate_Click(object sender, EventArgs e)
{
Random rnd = new();
_warship = new DrawingWarship();
_warship.Init(rnd.Next(100, 300), rnd.Next(1000, 2000), Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256)));
_warship.SetPosition(rnd.Next(10, 100), rnd.Next(10, 100), pictureBoxWarship.Width, pictureBoxWarship.Height);
toolStripStatusLabelSpeed.Text = $"Ñêîðîñòü: {_warship.Warship.Speed}";
toolStripStatusLabelWeight.Text = $"Âåñ: {_warship.Warship.Weight}";
toolStripStatusLabelBodyColor.Text = $"Öâåò: {_warship.Warship.BodyColor.Name}";
Color color = Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
_warship = new DrawingWarship(rnd.Next(100, 300), rnd.Next(1000, 2000), color);
SetData();
Draw();
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ ñòðåëî÷åê
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
string name = ((Button)sender)?.Name ?? string.Empty;
@ -64,5 +85,37 @@ namespace AircraftCarrier
_warship?.ChangeBorders(pictureBoxWarship.Width,pictureBoxWarship.Height);
Draw();
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Modification"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateModif_Click(object sender, EventArgs e)
{
Random rnd = new();
Color color = Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
Color dopColor = Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256));
ColorDialog dialogDop = new();
if (dialogDop.ShowDialog() == DialogResult.OK)
{
dopColor = dialogDop.Color;
}
_warship = new DrawingAircraftCarrier(rnd.Next(100, 300), rnd.Next(1000, 2000), color, dopColor,
Convert.ToBoolean(rnd.Next(0, 2)), Convert.ToBoolean(rnd.Next(0, 2)), Convert.ToBoolean(rnd.Next(0, 2)));
SetData();
Draw();
}
private void ButtonSelectWarship_Click(object sender, EventArgs e)
{
SelectedWarship = _warship;
DialogResult = DialogResult.OK;
}
}
}

View File

@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AircraftCarrier
{
/// <summary>
/// Интерфейс для работы с объектом, прорисовываемым на форме
/// </summary>
internal interface IDrawingObject
{
/// <summary>
/// Шаг перемещения объекта
/// </summary>
public float Step { get; }
/// <summary>
/// Установка позиции объекта
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
/// <param name="width">Ширина полотна</param>
/// <param name="height">Высота полотна</param>
void SetObject(int x, int y, int width, int height);
/// <summary>
/// Изменение направления пермещения объекта
/// </summary>
/// <param name="direction">Направление</param>
/// <returns></returns>
void MoveObject(Direction direction);
/// <summary>
/// Отрисовка объекта
/// </summary>
/// <param name="g"></param>
void DrawningObject(Graphics g);
/// <summary>
/// Получение текущей позиции объекта
/// </summary>
/// <returns></returns>
(float Left, float Right, float Top, float Bottom) GetCurrentPosition();
}
}

View File

@ -0,0 +1,63 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace AircraftCarrier
{
internal class LineMap : AbstractMap
{
/// <summary>
/// Цвет участка закрытого
/// </summary>
private readonly Brush barrierColor = new SolidBrush(Color.Brown);
/// <summary>
/// Цвет участка открытого
/// </summary>
private readonly Brush waterColor = new SolidBrush(Color.Blue);
protected override void DrawBarrierPart(Graphics g, int i, int j)
{
g.FillRectangle(barrierColor, i * _size_x, j * _size_y, _size_x, _size_y);
}
protected override void DrawRoadPart(Graphics g, int i, int j)
{
g.FillRectangle(waterColor, i * _size_x, j * _size_y, _size_x, _size_y);
}
protected override void GenerateMap()
{
_map = new int[100, 100];
_size_x = (float)_width / _map.GetLength(0);
_size_y = (float)_height / _map.GetLength(1);
int counter = 0;
for (int i = 0; i < _map.GetLength(0); ++i)
{
for (int j = 0; j < _map.GetLength(1); ++j)
{
_map[i, j] = _freeRoad;
}
}
bool flag = true;
while (counter < 20)
{
int lineX = _random.Next(11, 89);
int lineY = _random.Next(11, 89);
if (flag)
{
for (int i = lineY; i <= lineY + 10; i++)
_map[lineX, i] = _barrier;
flag = false;
}
else
{
for (int i = lineX; i <= lineX + 10; i++)
_map[i, lineY] = _barrier;
flag = true;
}
counter++;
}
}
}
}

View File

@ -0,0 +1,177 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AircraftCarrier
{
/// <summary>
/// Карта с набром объектов под нее
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
internal class MapWithSetWarshipsGeneric <T, U>
where T : class, IDrawingObject
where U : AbstractMap
{
/// <summary>
/// Ширина окна отрисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна отрисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Размер занимаемого объектом места (ширина)
/// </summary>
private readonly int _placeSizeWidth = 120;
/// <summary>
/// Размер занимаемого объектом места (высота)
/// </summary>
private readonly int _placeSizeHeight = 50;
/// <summary>
/// Набор объектов
/// </summary>
private readonly SetWarshipsGeneric<T> _setWarships;
/// <summary>
/// Карта
/// </summary>
private readonly U _map;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
/// <param name="map"></param>
public MapWithSetWarshipsGeneric(int picWidth, int picHeight, U map)
{
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_setWarships = new SetWarshipsGeneric<T>(width * height);
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_map = map;
}
/// <summary>
/// Перегрузка оператора сложения
/// </summary>
/// <param name="map"></param>
/// <param name="warship"></param>
/// <returns></returns>
public static int operator +(MapWithSetWarshipsGeneric<T, U> map, T warship)
{
return map._setWarships.Insert(warship);
}
/// <summary>
/// Перегрузка оператора вычитания
/// </summary>
/// <param name="map"></param>
/// <param name="position"></param>
/// <returns></returns>
public static T operator -(MapWithSetWarshipsGeneric<T, U> map, int position)
{
return map._setWarships.Remove(position);
}
/// <summary>
/// Вывод всего набора объектов
/// </summary>
/// <returns></returns>
public Bitmap ShowSet()
{
Bitmap bmp = new(_pictureWidth, _pictureHeight);
Graphics gr = Graphics.FromImage(bmp);
DrawBackground(gr);
DrawWarships(gr);
return bmp;
}
/// <summary>
/// Просмотр объекта на карте
/// </summary>
/// <returns></returns>
public Bitmap ShowOnMap()
{
Shaking();
foreach(var warship in _setWarships.GetWarships())
{
return _map.CreateMap(_pictureWidth, _pictureHeight, warship);
}
return new(_pictureWidth, _pictureHeight);
}
/// <summary>
/// Перемещение объекта по крате
/// </summary>
/// <param name="direction"></param>
/// <returns></returns>
public Bitmap MoveObject(Direction direction)
{
if (_map != null)
{
return _map.MoveObject(direction);
}
return new(_pictureWidth, _pictureHeight);
}
/// <summary>
/// "Взбалтываем" набор, чтобы все элементы оказались в начале
/// </summary>
private void Shaking()
{
int j = _setWarships.Count - 1;
for (int i = 0; i < _setWarships.Count; i++)
{
if (_setWarships[i] == null)
{
for (; j > i; j--)
{
var car = _setWarships[j];
if (car != null)
{
_setWarships.Insert(car, i);
_setWarships.Remove(j);
break;
}
}
if (j <= i)
{
return;
}
}
}
}
/// <summary>
/// Метод отрисовки фона
/// </summary>
/// <param name="g"></param>
private void DrawBackground(Graphics g)
{
Pen pen = new(Color.Black, 2);
g.FillRectangle(Brushes.Aqua, 0, 0, _pictureWidth, _pictureHeight);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight; ++j)
{//линия рамзетки места
g.DrawLine(pen, i * _placeSizeWidth + 20, j * _placeSizeHeight + 2, i * _placeSizeWidth + (int)(_placeSizeWidth * 0.8), j * _placeSizeHeight + 2);
g.DrawLine(pen, i * _placeSizeWidth + (int)(_placeSizeWidth * 0.8), j * _placeSizeHeight + 2, i * _placeSizeWidth + _placeSizeWidth, j * _placeSizeHeight + _placeSizeHeight / 2);
g.DrawLine(pen, i * _placeSizeWidth + _placeSizeWidth, j * _placeSizeHeight + _placeSizeHeight / 2, i * _placeSizeWidth + (int)(_placeSizeWidth * 0.8), j * _placeSizeHeight + _placeSizeHeight);
}
g.DrawLine(pen, i * _placeSizeWidth + 20, _pictureHeight / _placeSizeHeight * _placeSizeHeight + 2, i * _placeSizeWidth + (int)(_placeSizeWidth * 0.8), _pictureHeight / _placeSizeHeight * _placeSizeHeight + 2);
}
}
/// <summary>
/// Метод прорисовки объектов
/// </summary>
/// <param name="g"></param>
private void DrawWarships(Graphics g)
{
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
for (int i = 0; i < _setWarships.Count; i++)
{
var warship = _setWarships[i];
warship?.SetObject(i % _pictureWidth * _placeSizeWidth, (height - 1 - i / width) * _placeSizeHeight + 4, _pictureWidth, _pictureHeight);
warship?.DrawningObject(g);
}
}
}
}

View File

@ -0,0 +1,69 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AircraftCarrier
{
internal class MapsCollection
{
/// <summary>
/// Словарь (хранилище) с картами
/// </summary>
readonly Dictionary<string, MapWithSetWarshipsGeneric<DrawingObjectWarship, AbstractMap>> _mapStorages;
/// <summary>
/// Возвращение списка названий карт
/// </summary>
public List<string> Keys => _mapStorages.Keys.ToList();
/// <summary>
/// Ширина окна отрисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна отрисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="pictureWidth"></param>
/// <param name="pictureHeight"></param>
public MapsCollection(int pictureWidth, int pictureHeight)
{
_mapStorages = new Dictionary<string, MapWithSetWarshipsGeneric<DrawingObjectWarship, AbstractMap>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
/// <summary>
/// Добавление карты
/// </summary>
/// <param name="name">Название карты</param>
/// <param name="map">Карта</param>
public void AddMap(string name, AbstractMap map)
{
_mapStorages.Add(name, new(_pictureWidth, _pictureHeight, map));
}
/// <summary>
/// Удаление карты
/// </summary>
/// <param name="name">Название карты</param>
public void DelMap(string name)
{
_mapStorages.Remove(name);
}
/// <summary>
/// Доступ к докам
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public MapWithSetWarshipsGeneric<DrawingObjectWarship, AbstractMap> this[string ind]
{
get
{
_mapStorages.TryGetValue(ind, out var MapWithSetWarshipsGeneric);
return MapWithSetWarshipsGeneric;
}
}
}
}

View File

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

View File

@ -0,0 +1,106 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AircraftCarrier
{
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T"></typeparam>
internal class SetWarshipsGeneric<T>
where T : class
{
/// <summary>
/// Список объектов, которые храним
/// </summary>
private readonly List<T> _places;
/// <summary>
/// Количество объектов в списке
/// </summary>
public int Count => _places.Count;
private readonly int _maxCount;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
public SetWarshipsGeneric(int count)
{
_maxCount = count;
_places = new List<T>();
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="warship">Добавляемый военный корабль</param>
/// <returns></returns>
public int Insert(T warship)
{
return Insert(warship, 0);
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="warship">Добавляемый военный корабль</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public int Insert(T warship, int position)
{
if (position >= _maxCount || position < 0) return -1;
_places.Insert(position, warship);
return 1;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T Remove(int position)
{
if (position >= _maxCount || position < 0)
return null;
var result = _places[position];
_places.RemoveAt(position);
return result;
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T this[int position]
{
get
{
if (position >= _maxCount || position < 0) return null;
return _places[position];
}
set
{
Insert(value, position);
}
}
/// <summary>
/// Проход по набору до первого пустого
/// </summary>
/// <returns></returns>
public IEnumerable<T> GetWarships()
{
foreach(var warship in _places)
{
if(warship != null)
{
yield return warship;
}
else
{
yield break;
}
}
}
}
}

View File

@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AircraftCarrier
{
/// <summary>
/// Простая реализация абсрактного класса AbstractMap
/// </summary>
internal class SimpleMap : AbstractMap
{
/// <summary>
/// Цвет участка закрытого
/// </summary>
private readonly Brush barrierColor = new SolidBrush(Color.Brown);
/// <summary>
/// Цвет участка открытого
/// </summary>
private readonly Brush waterColor = new SolidBrush(Color.Blue);
protected override void DrawBarrierPart(Graphics g, int i, int j)
{
g.FillRectangle(barrierColor, i * _size_x, j * _size_y, i * (_size_x + 1), j * (_size_y + 1));
}
protected override void DrawRoadPart(Graphics g, int i, int j)
{
g.FillRectangle(waterColor, i * _size_x, j * _size_y, i * (_size_x + 1), j * (_size_y + 1));
}
protected override void GenerateMap()
{
_map = new int[100, 100];
_size_x = (float)_width / _map.GetLength(0);
_size_y = (float)_height / _map.GetLength(1);
int counter = 0;
for (int i = 0; i < _map.GetLength(0); ++i)
{
for (int j = 0; j < _map.GetLength(1); ++j)
{
_map[i, j] = _freeRoad;
}
}
while (counter < 50)
{
int x = _random.Next(0, 100);
int y = _random.Next(0, 100);
if (_map[x, y] == _freeRoad)
{
_map[x, y] = _barrier;
counter++;
}
}
}
}
}