Compare commits

...

15 Commits

Author SHA1 Message Date
the
07e133ab0d Fix 2022-12-09 16:29:49 +04:00
the
d78ff91551 revert 72ea3413da
revert revert d9bd7fc54d

revert Добавления, изменения
2022-12-09 14:35:40 +04:00
the
72ea3413da revert d9bd7fc54d
revert Добавления, изменения
2022-12-09 14:28:58 +04:00
the
fd9a9ed114 Fix2 2022-11-21 16:50:22 +04:00
the
3e84127331 Fix 2022-11-21 16:48:41 +04:00
the
c265d94f01 Исправление 2022-10-25 09:26:29 +04:00
the
45aa67a6bc Исправления 2022-10-11 10:38:13 +04:00
the
eae54734e1 Исправления 2022-10-11 09:03:31 +04:00
the
d9bd7fc54d Добавления, изменения 2022-10-11 08:47:14 +04:00
the
1bb6a06e74 Изменён тип возвращаемых значений. Добавлен фон и порядок прорисовки 2022-10-11 08:43:08 +04:00
the
0bb7f7a431 TODO 2022-10-03 09:45:14 +04:00
the
27ab04d2f6 Form changes 2022-10-02 20:12:08 +04:00
the
9be0242296 Интерфейсы, карты, форма для карт. 2022-10-02 16:45:18 +04:00
the
6196569b70 Прорисовка продвинутого объекта. 2022-09-27 10:59:08 +04:00
the
b9ad742c3f Переход на конструкторы 2022-09-27 09:34:26 +04:00
18 changed files with 1266 additions and 20 deletions

134
Ship/Ship/AbstractMap.cs Normal file
View File

@ -0,0 +1,134 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ship
{
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)
{
_drawingObject.MoveObject(direction);
if (ObjectIntersects())
{
switch (direction)
{
case Direction.Left:
_drawingObject.MoveObject(Direction.Right);
break;
case Direction.Right:
_drawingObject.MoveObject(Direction.Left);
break;
case Direction.Up:
_drawingObject.MoveObject(Direction.Down);
break;
case Direction.Down:
_drawingObject.MoveObject(Direction.Up);
break;
}
}
return DrawMapWithObject();
}
private bool ObjectIntersects()
{
var location = _drawingObject.GetCurrentPosition();
for (int i = 0; i < _map.GetLength(0); i++)
{
for (int j = 0; j < _map.GetLength(1); j++)
{
if (_map[i, j] == _barrier)
{
if (i * _size_x >= location.Left && (i + 1) * _size_x <= location.Right && j * _size_y >= location.Top && (j + 1) * _size_y <= location.Bottom)
{
return true;
}
}
}
}
return false;
}
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);
Rectangle rectObject = new Rectangle(x, y, 100, 100);
for (int i = 0; i < _map.GetLength(0); i++)
{
for (int j = 0; j < _map.GetLength(1); j++)
{
if (_map[i, j] == _barrier)
{
Rectangle rectBarrier = new Rectangle((int)(i * _size_x), (int)(j * _size_y), (int)_size_x, (int)_size_y);
if (rectObject.IntersectsWith(rectBarrier))
{
return false;
}
}
}
}
return true;
}
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 Ship
/// <summary>
/// Направление перемещения
/// </summary>
internal enum Direction
public enum Direction
{
None = 0,
Up = 1,
Down = 2,
Left = 3,

View File

@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ship
{
internal class DrawingMotorShip : DrawingShip
{
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Цвет кузова</param>
/// <param name="dopColor">Дополнительный цвет</param>
/// <param name="pipes">Признак наличия труб</param>
/// <param name="fuelTank">Признак наличия отсека для топлива</param>
public DrawingMotorShip(int speed, float weight, Color bodyColor, Color dopColor, bool pipes, bool fuelTank) : base(speed, weight, bodyColor, 110, 60)
{
Ship = new EntityMotorShip(speed, weight, bodyColor, dopColor, pipes, fuelTank);
}
public override void DrawTransport(Graphics g)
{
if (Ship is not EntityMotorShip motorShip)
{
return;
}
Pen pen = new(Color.Black);
Brush dopBrush = new SolidBrush(motorShip.DopColor);
if (motorShip.Pipes)
{
g.FillRectangle(dopBrush, _startPosX + 20, _startPosY + 20, 10, 30);
g.FillRectangle(dopBrush, _startPosX + 40, _startPosY + 10, 10, 40);
g.FillRectangle(dopBrush, _startPosX + 60, _startPosY + 20, 10, 30);
}
_startPosY += 40;
base.DrawTransport(g);
_startPosY -= 40;
if (motorShip.Fueltank)
{
g.FillEllipse(dopBrush, _startPosX + 40, _startPosY + 55, 20, 10);
}
}
}
}

View File

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

View File

@ -6,20 +6,20 @@ using System.Threading.Tasks;
namespace Ship
{
internal class DrawingShip
public class DrawingShip
{
/// <summary>
/// Класс-сущность
/// </summary>
public EntityShip Ship { private set; get; }
public EntityShip Ship { protected set; get; }
/// <summary>
/// Левая координата отрисовки корабля
/// </summary>
private float _startPosX;
protected float _startPosX;
/// <summary>
/// Верхняя кооридната отрисовки корабля
/// </summary>
private float _startPosY;
protected float _startPosY;
/// <summary>
/// Ширина окна отрисовки
/// </summary>
@ -42,11 +42,24 @@ namespace Ship
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес корабля</param>
/// <param name="bodyColor">Цвет корпуса</param>
public void Init(int speed, float weight, Color bodyColor)
public DrawingShip(int speed, float weight, Color bodyColor)
{
Ship = new EntityShip();
Ship.Init(speed, weight, bodyColor);
Ship = new EntityShip(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 DrawingShip(int speed, float weight, Color bodyColor, int shipWidth, int shipHeight) : this(speed, weight, bodyColor)
{
_shipWidth = shipWidth;
_shipHeight = shipHeight;
}
/// <summary>
/// Установка позиции корабля
/// </summary>
@ -120,7 +133,7 @@ namespace Ship
/// Отрисовка автомобиля
/// </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)
@ -165,5 +178,10 @@ namespace Ship
}
}
public (float Left, float Right, float Top, float Bottom) GetCurrentPosition()
{
return (_startPosX, _startPosX + _shipWidth, _startPosY, _startPosY + _shipHeight);
}
}
}

View File

@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ship
{
internal class EntityMotorShip : EntityShip
{
/// <summary>
/// Дополнительный цвет
/// </summary>
public Color DopColor { get; private set; }
/// <summary>
/// Признак наличия антикрыла
/// </summary>
public bool Pipes { get; private set; }
/// <summary>
/// Признак наличия гоночной полосы
/// </summary>
public bool Fueltank { get; private set; }
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Цвет кузова</param>
/// <param name="dopColor">Дополнительный цвет</param>
/// <param name="wing">Признак наличия антикрыла</param>
/// <param name="sportLine">Признак наличия гоночной полосы</param>
public EntityMotorShip(int speed, float weight, Color bodyColor, Color dopColor, bool pipes, bool fuelTank) : base(speed, weight, bodyColor)
{
DopColor = dopColor;
Pipes = pipes;
Fueltank = fuelTank;
}
}
}

View File

@ -6,7 +6,7 @@ using System.Threading.Tasks;
namespace Ship
{
internal class EntityShip
public class EntityShip
{
/// <summary>
/// Скорость
@ -31,7 +31,7 @@ namespace Ship
/// <param name="weight"></param>
/// <param name="bodyColor"></param>
/// <returns></returns>
public void Init(int speed, float weight, Color bodyColor)
public EntityShip(int speed, float weight, Color bodyColor)
{
Random rnd = new();
Speed = speed <= 0 ? rnd.Next(50, 150) : speed;

217
Ship/Ship/FormMapWithSetShips.Designer.cs generated Normal file
View File

@ -0,0 +1,217 @@
namespace Ship
{
partial class FormMapWithSetShips
{
/// <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.buttonRight = new System.Windows.Forms.Button();
this.buttonDown = new System.Windows.Forms.Button();
this.buttonLeft = new System.Windows.Forms.Button();
this.buttonUp = new System.Windows.Forms.Button();
this.buttonShowOnMap = new System.Windows.Forms.Button();
this.buttonShowStorage = new System.Windows.Forms.Button();
this.buttonRemoveShip = new System.Windows.Forms.Button();
this.maskedTextBoxPosition = new System.Windows.Forms.MaskedTextBox();
this.buttonAddShip = new System.Windows.Forms.Button();
this.comboBoxSelectorMap = new System.Windows.Forms.ComboBox();
this.pictureBox = new System.Windows.Forms.PictureBox();
this.groupBoxTools.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
this.SuspendLayout();
//
// groupBoxTools
//
this.groupBoxTools.Controls.Add(this.buttonRight);
this.groupBoxTools.Controls.Add(this.buttonDown);
this.groupBoxTools.Controls.Add(this.buttonLeft);
this.groupBoxTools.Controls.Add(this.buttonUp);
this.groupBoxTools.Controls.Add(this.buttonShowOnMap);
this.groupBoxTools.Controls.Add(this.buttonShowStorage);
this.groupBoxTools.Controls.Add(this.buttonRemoveShip);
this.groupBoxTools.Controls.Add(this.maskedTextBoxPosition);
this.groupBoxTools.Controls.Add(this.buttonAddShip);
this.groupBoxTools.Controls.Add(this.comboBoxSelectorMap);
this.groupBoxTools.Dock = System.Windows.Forms.DockStyle.Right;
this.groupBoxTools.Location = new System.Drawing.Point(600, 0);
this.groupBoxTools.Name = "groupBoxTools";
this.groupBoxTools.Size = new System.Drawing.Size(200, 450);
this.groupBoxTools.TabIndex = 0;
this.groupBoxTools.TabStop = false;
this.groupBoxTools.Text = "Инструменты";
//
// buttonRight
//
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::Ship.Properties.Resources.arrowRight;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonRight.Location = new System.Drawing.Point(124, 408);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(30, 30);
this.buttonRight.TabIndex = 10;
this.buttonRight.UseVisualStyleBackColor = true;
this.buttonRight.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::Ship.Properties.Resources.arrowDown;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonDown.Location = new System.Drawing.Point(88, 408);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(30, 30);
this.buttonDown.TabIndex = 9;
this.buttonDown.UseVisualStyleBackColor = true;
this.buttonDown.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::Ship.Properties.Resources.arrowLeft;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonLeft.Location = new System.Drawing.Point(52, 408);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(30, 30);
this.buttonLeft.TabIndex = 8;
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::Ship.Properties.Resources.arrowUp;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonUp.Location = new System.Drawing.Point(88, 372);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(30, 30);
this.buttonUp.TabIndex = 7;
this.buttonUp.UseVisualStyleBackColor = true;
this.buttonUp.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonShowOnMap
//
this.buttonShowOnMap.Location = new System.Drawing.Point(19, 315);
this.buttonShowOnMap.Name = "buttonShowOnMap";
this.buttonShowOnMap.Size = new System.Drawing.Size(169, 37);
this.buttonShowOnMap.TabIndex = 5;
this.buttonShowOnMap.Text = "Посмотреть карту";
this.buttonShowOnMap.UseVisualStyleBackColor = true;
this.buttonShowOnMap.Click += new System.EventHandler(this.ButtonShowOnMap_Click);
//
// buttonShowStorage
//
this.buttonShowStorage.Location = new System.Drawing.Point(19, 240);
this.buttonShowStorage.Name = "buttonShowStorage";
this.buttonShowStorage.Size = new System.Drawing.Size(169, 37);
this.buttonShowStorage.TabIndex = 4;
this.buttonShowStorage.Text = "Посмотреть хранилище";
this.buttonShowStorage.UseVisualStyleBackColor = true;
this.buttonShowStorage.Click += new System.EventHandler(this.ButtonShowStorage_Click);
//
// buttonRemoveShip
//
this.buttonRemoveShip.Location = new System.Drawing.Point(19, 166);
this.buttonRemoveShip.Name = "buttonRemoveShip";
this.buttonRemoveShip.Size = new System.Drawing.Size(169, 37);
this.buttonRemoveShip.TabIndex = 3;
this.buttonRemoveShip.Text = "Удалить корабль";
this.buttonRemoveShip.UseVisualStyleBackColor = true;
this.buttonRemoveShip.Click += new System.EventHandler(this.ButtonRemoveShip_Click);
//
// maskedTextBoxPosition
//
this.maskedTextBoxPosition.Location = new System.Drawing.Point(19, 137);
this.maskedTextBoxPosition.Mask = "00";
this.maskedTextBoxPosition.Name = "maskedTextBoxPosition";
this.maskedTextBoxPosition.Size = new System.Drawing.Size(169, 23);
this.maskedTextBoxPosition.TabIndex = 2;
//
// buttonAddShip
//
this.buttonAddShip.Location = new System.Drawing.Point(19, 94);
this.buttonAddShip.Name = "buttonAddShip";
this.buttonAddShip.Size = new System.Drawing.Size(169, 37);
this.buttonAddShip.TabIndex = 1;
this.buttonAddShip.Text = "Добавить корабль";
this.buttonAddShip.UseVisualStyleBackColor = true;
this.buttonAddShip.Click += new System.EventHandler(this.ButtonAddShip_Click);
//
// 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(19, 22);
this.comboBoxSelectorMap.Name = "comboBoxSelectorMap";
this.comboBoxSelectorMap.Size = new System.Drawing.Size(169, 23);
this.comboBoxSelectorMap.TabIndex = 0;
this.comboBoxSelectorMap.SelectedIndexChanged += new System.EventHandler(this.ComboBoxSelectorMap_SelectedIndexChanged);
//
// 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(600, 450);
this.pictureBox.TabIndex = 1;
this.pictureBox.TabStop = false;
//
// FormMapWithSetShips
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.pictureBox);
this.Controls.Add(this.groupBoxTools);
this.Name = "FormMapWithSetShips";
this.Text = "FormMapWithSetShips";
this.Load += new System.EventHandler(this.FormMapWithSetShips_Load);
this.groupBoxTools.ResumeLayout(false);
this.groupBoxTools.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
this.ResumeLayout(false);
}
#endregion
private GroupBox groupBoxTools;
private Button buttonShowOnMap;
private Button buttonShowStorage;
private Button buttonRemoveShip;
private MaskedTextBox maskedTextBoxPosition;
private Button buttonAddShip;
private ComboBox comboBoxSelectorMap;
private PictureBox pictureBox;
private Button buttonRight;
private Button buttonDown;
private Button buttonLeft;
private Button buttonUp;
}
}

View File

@ -0,0 +1,169 @@
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 Ship
{
public partial class FormMapWithSetShips : Form
{
/// <summary>
/// Объект от класса карты с набором объектов
/// </summary>
private MapWithSetShipsGeneric<DrawingObject, AbstractMap> _mapShipsCollectionGeneric;
/// <summary>
/// Конструктор
/// </summary>
public FormMapWithSetShips()
{
InitializeComponent();
}
/// <summary>
/// Выбор карты
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ComboBoxSelectorMap_SelectedIndexChanged(object sender, EventArgs e)
{
AbstractMap map = null;
switch (comboBoxSelectorMap.Text)
{
case "Простая карта":
map = new SimpleMap();
break;
case "Водная карта":
map = new WaterMap();
break;
}
if (map != null)
{
_mapShipsCollectionGeneric = new
MapWithSetShipsGeneric<DrawingObject, AbstractMap>(pictureBox.Width, pictureBox.Height, map);
}
else
{
_mapShipsCollectionGeneric = null;
}
}
/// <summary>
/// Добавление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddShip_Click(object sender, EventArgs e)
{
if (_mapShipsCollectionGeneric == null)
{
return;
}
FormShip form = new();
if (form.ShowDialog() == DialogResult.OK)
{
DrawingObject car = new(form.SelectedShip);
if (_mapShipsCollectionGeneric + car != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _mapShipsCollectionGeneric.ShowSet();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
}
/// <summary>
/// Удаление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveShip_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(maskedTextBoxPosition.Text))
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_mapShipsCollectionGeneric - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _mapShipsCollectionGeneric.ShowSet();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
/// <summary>
/// Вывод набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonShowStorage_Click(object sender, EventArgs e)
{
if (_mapShipsCollectionGeneric == null)
{
return;
}
pictureBox.Image = _mapShipsCollectionGeneric.ShowSet();
}
/// <summary>
/// Вывод карты
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonShowOnMap_Click(object sender, EventArgs e)
{
if (_mapShipsCollectionGeneric == null)
{
return;
}
pictureBox.Image = _mapShipsCollectionGeneric.ShowOnMap();
}
/// <summary>
/// Перемещение
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_mapShipsCollectionGeneric == null)
{
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 = _mapShipsCollectionGeneric.MoveObject(dir);
}
private void FormMapWithSetShips_Load(object sender, EventArgs e)
{
}
}
}

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.buttonLeft = new System.Windows.Forms.Button();
this.buttonDown = new System.Windows.Forms.Button();
this.buttonRight = new System.Windows.Forms.Button();
this.buttonCreateModif = new System.Windows.Forms.Button();
this.buttonSelectShip = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxShip)).BeginInit();
this.statusStrip.SuspendLayout();
this.SuspendLayout();
@ -141,11 +143,33 @@
this.buttonRight.UseVisualStyleBackColor = true;
this.buttonRight.Click += new System.EventHandler(this.buttonMove_Click);
//
// buttonCreateModif
//
this.buttonCreateModif.Location = new System.Drawing.Point(93, 402);
this.buttonCreateModif.Name = "buttonCreateModif";
this.buttonCreateModif.Size = new System.Drawing.Size(101, 23);
this.buttonCreateModif.TabIndex = 7;
this.buttonCreateModif.Text = "Модификация";
this.buttonCreateModif.UseVisualStyleBackColor = true;
this.buttonCreateModif.Click += new System.EventHandler(this.buttonCreateModif_Click);
//
// buttonSelectShip
//
this.buttonSelectShip.Location = new System.Drawing.Point(605, 402);
this.buttonSelectShip.Name = "buttonSelectShip";
this.buttonSelectShip.Size = new System.Drawing.Size(75, 23);
this.buttonSelectShip.TabIndex = 8;
this.buttonSelectShip.Text = "Выбрать";
this.buttonSelectShip.UseVisualStyleBackColor = true;
this.buttonSelectShip.Click += new System.EventHandler(this.buttonSelectShip_Click);
//
// FormShip
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.buttonSelectShip);
this.Controls.Add(this.buttonCreateModif);
this.Controls.Add(this.buttonRight);
this.Controls.Add(this.buttonDown);
this.Controls.Add(this.buttonLeft);
@ -155,6 +179,7 @@
this.Controls.Add(this.statusStrip);
this.Name = "FormShip";
this.Text = "Корабль";
this.Load += new System.EventHandler(this.FormShip_Load);
((System.ComponentModel.ISupportInitialize)(this.pictureBoxShip)).EndInit();
this.statusStrip.ResumeLayout(false);
this.statusStrip.PerformLayout();
@ -175,5 +200,7 @@
private Button buttonLeft;
private Button buttonDown;
private Button buttonRight;
private Button buttonCreateModif;
private Button buttonSelectShip;
}
}

View File

@ -4,6 +4,8 @@ namespace Ship
{
private DrawingShip _ship;
public DrawingShip SelectedShip { get; private set; }
public FormShip()
{
InitializeComponent();
@ -19,6 +21,15 @@ namespace Ship
pictureBoxShip.Image = bmp;
}
/// <summary>
/// Ěĺňîä óńňŕíîâęč äŕííűő
/// </summary>
private void SetData()
{
toolStripStatusLabelSpeed.Text = $"Ńęîđîńňü: {_ship.Ship.Speed}";
toolStripStatusLabelWeight.Text = $"Âĺń: {_ship.Ship.Weight}";
toolStripStatusLabelColor.Text = $"Öâĺň: {_ship.Ship.BodyColor.Name}";
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü"
/// </summary>
/// <param name="sender"></param>
@ -26,15 +37,17 @@ namespace Ship
private void buttonCreate_Click(object sender, EventArgs e)
{
Random rnd = new();
_ship = new DrawingShip();
_ship.Init(rnd.Next(100, 300), rnd.Next(1000, 2000),
Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256)));
_ship.SetPosition(rnd.Next(10, 100), pictureBoxShip.Height - rnd.Next(20, 100),
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;
}
_ship = new DrawingShip(rnd.Next(100, 300), rnd.Next(1000, 2000), color);
_ship.SetPosition(rnd.Next(10, 100), pictureBoxShip.Height - rnd.Next(50, 100),
pictureBoxShip.Width, pictureBoxShip.Height);
toolStripStatusLabelSpeed.Text = $"Ñêîðîñòü: {_ship.Ship.Speed}";
toolStripStatusLabelWeight.Text = $"Âåñ: {_ship.Ship.Weight}";
toolStripStatusLabelColor.Text = $"Öâåò: { _ship.Ship.BodyColor.Name}";
Draw();
SetData();
Draw();
}
/// <summary>
/// Èçìåíåíèå ðàçìåðîâ ôîðìû
@ -72,5 +85,41 @@ namespace Ship
_ship?.ChangeBorders(pictureBoxShip.Width, pictureBoxShip.Height);
Draw();
}
/// <summary>
/// Îáđŕáîňęŕ íŕćŕňč˙ ęíîďęč "Ěîäčôčęŕöč˙"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCreateModif_Click(object sender, EventArgs e)
{
Random rnd = new();
Color colorMain = Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256));
Color colorAdd = Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
colorMain = dialog.Color;
}
if (dialog.ShowDialog() == DialogResult.OK)
{
colorAdd = dialog.Color;
}
_ship = new DrawingMotorShip(rnd.Next(100, 300), rnd.Next(1000, 2000), colorMain, colorAdd, Convert.ToBoolean(rnd.Next(0, 2)), Convert.ToBoolean(rnd.Next(0, 2)));
_ship.SetPosition(rnd.Next(50, 100), pictureBoxShip.Height - rnd.Next(80, 100), pictureBoxShip.Width, pictureBoxShip.Height);
SetData();
Draw();
}
private void FormShip_Load(object sender, EventArgs e)
{
}
private void buttonSelectShip_Click(object sender, EventArgs e)
{
SelectedShip = _ship;
DialogResult = DialogResult.OK;
}
}
}

View File

@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ship
{
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,188 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ship
{
internal class MapWithSetShipsGeneric<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 = 210;
/// <summary>
/// Размер занимаемого объектом места (высота)
/// </summary>
private readonly int _placeSizeHeight = 90;
/// <summary>
/// Набор объектов
/// </summary>
private readonly SetShipsGeneric<T> _setShips;
/// <summary>
/// Карта
/// </summary>
private readonly U _map;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
/// <param name="map"></param>
public MapWithSetShipsGeneric(int picWidth, int picHeight, U map)
{
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_setShips = new SetShipsGeneric<T>(width * height);
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_map = map;
}
/// <summary>
/// Перегрузка оператора сложения
/// </summary>
/// <param name="map"></param>
/// <param name="car"></param>
/// <returns></returns>
public static int operator +(MapWithSetShipsGeneric<T, U> map, T car)
{
return map._setShips.Insert(car);
}
/// <summary>
/// Перегрузка оператора вычитания
/// </summary>
/// <param name="map"></param>
/// <param name="position"></param>
/// <returns></returns>
public static T operator -(MapWithSetShipsGeneric<T, U> map, int
position)
{
return map._setShips.Remove(position);
}
/// <summary>
/// Вывод всего набора объектов
/// </summary>
/// <returns></returns>
public Bitmap ShowSet()
{
Shaking();
Bitmap bmp = new(_pictureWidth, _pictureHeight);
Graphics gr = Graphics.FromImage(bmp);
DrawBackground(gr);
DrawShips(gr);
return bmp;
}
/// <summary>
/// Просмотр объекта на карте
/// </summary>
/// <returns></returns>
public Bitmap ShowOnMap()
{
Shaking();
for (int i = 0; i < _setShips.Count; i++)
{
var car = _setShips.Get(i);
if (car != null)
{
return _map.CreateMap(_pictureWidth, _pictureHeight, car);
}
}
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 = _setShips.Count - 1;
for (int i = 0; i < _setShips.Count; i++)
{
if (_setShips.Get(i) == null)
{
for (; j > i; j--)
{
var car = _setShips.Get(j);
if (car != null)
{
_setShips.Insert(car, i);
_setShips.Remove(j);
break;
}
}
if (j <= i)
{
return;
}
}
}
}
/// <summary>
/// Метод отрисовки фона
/// </summary>
/// <param name="g"></param>
private void DrawBackground(Graphics g)
{
Pen pen = new(Color.Black, 3);
Brush seaBrush = new SolidBrush(Color.Blue);
Pen thickPen = new Pen(Color.Black, 8);
Pen thinPen = new Pen(Color.Black, 4);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j)
{//линия рамзетки места
g.DrawLine(pen, i * _placeSizeWidth, j * _placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth / 2, j * _placeSizeHeight);
g.FillRectangle(seaBrush, i * _placeSizeWidth, j * _placeSizeHeight + _placeSizeHeight * 3 / 4 - 5, _placeSizeWidth / 2, _placeSizeHeight / 3);
g.DrawLine(thickPen, i * _placeSizeWidth, j * _placeSizeHeight - 45, i * _placeSizeWidth + _placeSizeWidth / 2 - 50, j * _placeSizeHeight - 45);
g.DrawLine(thinPen, i * _placeSizeWidth + 10, j * _placeSizeHeight - 45, i * _placeSizeWidth + 10, j * _placeSizeHeight - 60);
g.DrawLine(thinPen, i * _placeSizeWidth + 20, j * _placeSizeHeight - 45, i * _placeSizeWidth + 20, j * _placeSizeHeight - 60);
g.DrawLine(thinPen, i * _placeSizeWidth + 30, j * _placeSizeHeight - 45, i * _placeSizeWidth + 30, j * _placeSizeHeight - 60);
g.DrawLine(thinPen, i * _placeSizeWidth + 40, j * _placeSizeHeight - 45, i * _placeSizeWidth + 40, j * _placeSizeHeight - 60);
}
g.DrawLine(pen, i * _placeSizeWidth, 0, i * _placeSizeWidth, (_pictureHeight / _placeSizeHeight) * _placeSizeHeight);
}
}
/// <summary>
/// Метод прорисовки объектов
/// </summary>
/// <param name="g"></param>
private void DrawShips(Graphics g)
{
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
for (int i = 0; i < _setShips.Count; i++)
{
var ship = _setShips.Get(i);
if (ship != null)
{
ship.SetObject((width - i % width - 1) * _placeSizeWidth + 10, (i / width) * _placeSizeHeight + 10, _pictureWidth, _pictureHeight);
ship.DrawningObject(g);
}
}
}
}
}

View File

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

View File

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

53
Ship/Ship/SimpleMap.cs Normal file
View File

@ -0,0 +1,53 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ship
{
internal class SimpleMap : AbstractMap
{
/// <summary>
/// Цвет участка закрытого
/// </summary>
private readonly Brush barrierColor = new SolidBrush(Color.White);
/// <summary>
/// Цвет участка открытого
/// </summary>
private readonly Brush roadColor = new SolidBrush(Color.Gray);
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(roadColor, 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++;
}
}
}
}
}

51
Ship/Ship/WaterMap.cs Normal file
View File

@ -0,0 +1,51 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ship
{
internal class WaterMap : AbstractMap
{
private readonly Brush barrierColor = new SolidBrush(Color.Red);
private readonly Brush roadColor = 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(roadColor, i * _size_x, j * _size_y, i * (_size_x + 1), j * (_size_y + 1));
}
protected override void GenerateMap()
{
_map = new int[50, 50];
_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 < 10)
{
int x = _random.Next(2, 48);
int y = _random.Next(3, 48);
var points = new int[] { _map[x, y], _map[x, y + 1], _map[x - 1, y + 1], _map[x + 1, y + 1] };
var forComparison = new int[] { _freeRoad, _freeRoad, _freeRoad, _freeRoad };
if (points.SequenceEqual(forComparison))
{
_map[x, y] = _barrier;
_map[x, y + 1] = _barrier;
_map[x + 1, y + 1] = _barrier;
_map[x - 1, y + 1] = _barrier;
counter++;
}
}
}
}
}