Compare commits

...

7 Commits

19 changed files with 1429 additions and 21 deletions

View File

@ -0,0 +1,158 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Stormtrooper
{
internal abstract class AbstractMap
{
private IDrawningObject _drawningObject = 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, IDrawningObject
drawningObject)
{
_width = width;
_height = height;
_drawningObject = drawningObject;
GenerateMap();
while (!SetObjectOnMap())
{
GenerateMap();
}
return DrawMapWithObject();
}
public Bitmap MoveObject(Direction direction)
{
int LefTopX = Convert.ToInt32(_drawningObject.GetCurrentPosition().Left / _size_x);
int LefTopY = Convert.ToInt32(_drawningObject.GetCurrentPosition().Top / _size_y);
int objwidth = Convert.ToInt32(_drawningObject.GetCurrentPosition().Right / _size_x);
int objheigh = Convert.ToInt32(_drawningObject.GetCurrentPosition().Bottom / _size_y);
bool CanStep = true;
switch (direction)
{
case Direction.Left:
for (int i = LefTopX; i >= Math.Abs(LefTopX - Convert.ToInt32(_drawningObject.Step / _size_x)); i--)
{
for (int j = LefTopY; j <= objheigh && j<_map.GetLength(1); j++)
{
if (_map[i, j] == _barrier)
{
CanStep = false;
break;
}
}
}
break;
case Direction.Right:
for (int i = objwidth; i <= objwidth + Convert.ToInt32(_drawningObject.Step / _size_x) && i < _map.GetLength(0); i++)
{
for (int j = LefTopY; j <= objheigh && j < _map.GetLength(1); j++)
{
if (_map[i, j] == _barrier)
{
CanStep = false;
break;
}
}
}
break;
case Direction.Down:
for (int i = LefTopX; i <= objwidth && i < _map.GetLength(0); i++)
{
for (int j = objheigh; j <= objheigh + Convert.ToInt32(_drawningObject.Step / _size_y) && j < _map.GetLength(1); j++)
{
if (_map[i, j] == _barrier)
{
CanStep = false;
break;
}
}
}
break;
case Direction.Up:
for (int i = LefTopX; i <= objwidth && i<_map.GetLength(0); i++)
{
for (int j = LefTopY; j >= Math.Abs(LefTopY - Convert.ToInt32(_drawningObject.Step / _size_y)) ; j--)
{
if (_map[i, j] == _barrier)
{
CanStep = false;
break;
}
}
}
break;
}
if (CanStep)
{
_drawningObject.MoveObject(direction);
}
return DrawMapWithObject();
}
private bool SetObjectOnMap()
{
if (_drawningObject == null || _map == null)
{
return false;
}
int x = _random.Next(0, 150);
int y = _random.Next(100, 300);
for (int i = 0; i < _map.GetLength(0); ++i)
{
for (int j = 0; j < _map.GetLength(1); ++j)
{
if (i * _size_x >= x && j * _size_y <= y &&
i * _size_x <= x + _drawningObject.GetCurrentPosition().Right &&
j * _size_y >= j - _drawningObject.GetCurrentPosition().Bottom && _map[i, j] == _barrier)
{
return false;
}
}
}
_drawningObject.SetObject(x, y, _width, _height);
return true;
}
private Bitmap DrawMapWithObject()
{
Bitmap bmp = new(_width, _height);
if (_drawningObject == 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)
DrawRoadPart(gr, i, j);
for (int i = 0; i < _map.GetLength(0); ++i)
for (int j = 0; j < _map.GetLength(1); ++j)
if (_map[i, j] == 1) DrawBarrierPart(gr, i, j);
_drawningObject.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 Stormtrooper
/// <summary>
/// Направление перемещения
/// </summary>
internal enum Direction
public enum Direction
{
None = 0,
Up = 1,
Down = 2,
Left = 3,

View File

@ -12,17 +12,17 @@ namespace Stormtrooper
/// <summary>
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
/// </summary>
internal class Drawning
public class Drawning
{
public EntityStormtrooper Storm { get; private set; }
public EntityStormtrooper Storm { get; protected set; }
/// <summary>
/// Левая координата отрисовки самолёта
/// </summary>
private float _startPosX;
protected float _startPosX;
/// <summary>
/// Нижняя кооридната отрисовки самолёта
/// </summary>
private float _startPosY;
protected float _startPosY;
/// <summary>
/// Ширина окна отрисовки
/// </summary>
@ -45,10 +45,23 @@ namespace Stormtrooper
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес самолёта</param>
/// <param name="bodyColor">Цвет кузова</param>
public void Init(int speed, float weight, Color bodyColor)
public Drawning(int speed, float weight, Color bodyColor)
{
Storm = new EntityStormtrooper();
Storm.Init(speed, weight, bodyColor);
Storm = new EntityStormtrooper(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 Drawning(int speed, float weight, Color bodyColor, int stormWidth, int stormHeight) :
this(speed, weight, bodyColor)
{
_StormWidth = stormWidth;
_StormHeight = stormHeight;
}
/// <summary>
/// Установка позиции самолёта
@ -117,7 +130,7 @@ namespace Stormtrooper
/// Отрисовка штурмовика
/// </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)
@ -162,7 +175,7 @@ namespace Stormtrooper
g.FillPolygon(brBl, N);
//фюзеляж
Brush brGr = new SolidBrush(Color.Gray);
Brush brGr = new SolidBrush(Color.White);
g.FillRectangle(brGr, _startPosX + 20, _startPosY - 60, 100, 20);
//крыло и стаб
@ -171,6 +184,7 @@ namespace Stormtrooper
g.FillPolygon(br, S);
}
/// <summary>
/// Смена границ формы отрисовки
/// </summary>
@ -195,5 +209,13 @@ namespace Stormtrooper
_startPosY = _pictureHeight.Value - _StormHeight;
}
}
/// <summary>
/// Получение текущей позиции объекта
/// </summary>
/// <returns></returns>
public (float Left, float Right, float Top, float Bottom) GetCurrentPosition()
{
return (_startPosX, _startPosX + _StormWidth, _startPosY - _StormHeight, _startPosY);
}
}
}

View File

@ -0,0 +1,66 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Stormtrooper
{
internal class DrawningMilitary : Drawning
{
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес самолёта</param>
/// <param name="bodyColor">Цвет кузова</param>
/// <param name="dopColor">Дополнительный цвет</param>
/// <param name="bodyKit">Признак наличия обвеса</param>
/// <param name="rocket">Признак наличия антикрыла</param>
/// <param name="sportLine">Признак наличия гоночной полосы</param>
public DrawningMilitary(int speed, float weight, Color bodyColor, Color dopColor, bool bodyKit, bool rocket, bool sportLine) :
base(speed, weight, bodyColor, 135, 100)
{
Storm = new EntityMilitaryStormtrooper(speed, weight, bodyColor, dopColor, bodyKit, rocket, sportLine);
}
public override void DrawTransport(Graphics g)
{
if (Storm is not EntityMilitaryStormtrooper militaryTrop)
{
return;
}
Pen pen = new(Color.Black);
Brush dopBrush = new SolidBrush(militaryTrop.DopColor);
if (militaryTrop.BodyKit)
{
g.DrawEllipse(pen, _startPosX - 2, _startPosY - 70, 5, 20);
g.DrawEllipse(pen, _startPosX - 2, _startPosY - 50, 5, 20);
g.FillEllipse(dopBrush, _startPosX - 2, _startPosY - 70, 5, 20);
g.FillEllipse(dopBrush, _startPosX - 2, _startPosY - 50, 5, 20);
}
_startPosX += 2;
base.DrawTransport(g);
_startPosX -= 2;
if (militaryTrop.Rocket)
{
g.FillRectangle(dopBrush, _startPosX + 50, _startPosY - 70, 40, 3);
g.FillRectangle(dopBrush, _startPosX + 50, _startPosY - 90, 40, 3);
g.FillRectangle(dopBrush, _startPosX + 50, _startPosY - 30, 40, 3);
g.FillRectangle(dopBrush, _startPosX + 50, _startPosY - 10, 40, 3);
}
if (militaryTrop.SportLine)
{
g.FillRectangle(dopBrush, _startPosX + 30, _startPosY - 60, 8, 20);
g.FillRectangle(dopBrush, _startPosX + 100, _startPosY - 60, 8, 20);
}
}
}
}

View File

@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Stormtrooper
{
internal class DrawningObjectStorm : IDrawningObject
{
private Drawning _storm = null;
public DrawningObjectStorm(Drawning storm)
{
_storm = storm;
}
public float Step => _storm?.Storm?.Step ?? 0;
public (float Left, float Right, float Top, float Bottom) GetCurrentPosition()
{
return _storm?.GetCurrentPosition() ?? default;
}
public void MoveObject(Direction direction)
{
_storm?.MoveTransport(direction);
}
public void SetObject(int x, int y, int width, int height)
{
_storm.SetPosition(x, y, width, height);
}
void IDrawningObject.DrawningObject(Graphics g)
{
if (_storm is DrawningMilitary)
((DrawningMilitary)_storm).DrawTransport(g);
_storm.DrawTransport(g);
}
}
}

View File

@ -0,0 +1,47 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Stormtrooper
{
internal class EntityMilitaryStormtrooper : EntityStormtrooper
{
/// <summary>
/// Дополнительный цвет
/// </summary>
public Color DopColor { get; private set; }
/// <summary>
/// Признак наличия обвеса
/// </summary>
public bool BodyKit { get; private set; }
/// <summary>
/// Признак наличия рокет
/// </summary>
public bool Rocket { get; private set; }
/// <summary>
/// Признак наличия полосы
/// </summary>
public bool SportLine { 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="rocket">Признак наличия рокет</param>
/// <param name="sportLine">Признак наличия гоночной полосы</param>
public EntityMilitaryStormtrooper(int speed, float weight, Color bodyColor, Color
dopColor, bool bodyKit, bool rocket, bool sportLine) :
base(speed, weight, bodyColor)
{
DopColor = dopColor;
BodyKit = bodyKit;
Rocket = rocket;
SportLine = sportLine;
}
}
}

View File

@ -9,7 +9,7 @@ namespace Stormtrooper
/// <summary>
/// Класс-сущность "Штурмовик"
/// </summary>
internal class EntityStormtrooper
public class EntityStormtrooper
{
/// <summary>
/// Скорость
@ -34,7 +34,7 @@ namespace Stormtrooper
/// <param name="weight"></param>
/// <param name="bodyColor"></param>
/// <returns></returns>
public void Init(int speed, float weight, Color bodyColor)
public EntityStormtrooper(int speed, float weight, Color bodyColor)
{
Random rnd = new Random();
Speed = speed <= 0 ? rnd.Next(50, 150) : speed;

View File

@ -0,0 +1,230 @@
namespace Stormtrooper
{
partial class FormMapWithSetStormtroopers
{
/// <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.maskedTextBoxPosition = new System.Windows.Forms.MaskedTextBox();
this.buttonRemoveStorm = new System.Windows.Forms.Button();
this.buttonShowStorage = new System.Windows.Forms.Button();
this.buttonDown = 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.buttonShowOnMap = new System.Windows.Forms.Button();
this.buttonAddStorm = 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.maskedTextBoxPosition);
this.groupBoxTools.Controls.Add(this.buttonRemoveStorm);
this.groupBoxTools.Controls.Add(this.buttonShowStorage);
this.groupBoxTools.Controls.Add(this.buttonDown);
this.groupBoxTools.Controls.Add(this.buttonRight);
this.groupBoxTools.Controls.Add(this.buttonLeft);
this.groupBoxTools.Controls.Add(this.buttonUp);
this.groupBoxTools.Controls.Add(this.buttonShowOnMap);
this.groupBoxTools.Controls.Add(this.buttonAddStorm);
this.groupBoxTools.Controls.Add(this.comboBoxSelectorMap);
this.groupBoxTools.Dock = System.Windows.Forms.DockStyle.Right;
this.groupBoxTools.Location = new System.Drawing.Point(927, 0);
this.groupBoxTools.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.groupBoxTools.Name = "groupBoxTools";
this.groupBoxTools.Padding = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.groupBoxTools.Size = new System.Drawing.Size(233, 739);
this.groupBoxTools.TabIndex = 0;
this.groupBoxTools.TabStop = false;
this.groupBoxTools.Text = "Инструменты";
//
// maskedTextBoxPosition
//
this.maskedTextBoxPosition.Location = new System.Drawing.Point(19, 221);
this.maskedTextBoxPosition.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.maskedTextBoxPosition.Mask = "00";
this.maskedTextBoxPosition.Name = "maskedTextBoxPosition";
this.maskedTextBoxPosition.Size = new System.Drawing.Size(199, 27);
this.maskedTextBoxPosition.TabIndex = 2;
this.maskedTextBoxPosition.ValidatingType = typeof(int);
//
// buttonRemoveStorm
//
this.buttonRemoveStorm.Location = new System.Drawing.Point(19, 260);
this.buttonRemoveStorm.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonRemoveStorm.Name = "buttonRemoveStorm";
this.buttonRemoveStorm.Size = new System.Drawing.Size(200, 47);
this.buttonRemoveStorm.TabIndex = 3;
this.buttonRemoveStorm.Text = "Удалить самолёт";
this.buttonRemoveStorm.UseVisualStyleBackColor = true;
this.buttonRemoveStorm.Click += new System.EventHandler(this.ButtonRemoveStorm_Click);
//
// buttonShowStorage
//
this.buttonShowStorage.Location = new System.Drawing.Point(19, 383);
this.buttonShowStorage.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonShowStorage.Name = "buttonShowStorage";
this.buttonShowStorage.Size = new System.Drawing.Size(200, 47);
this.buttonShowStorage.TabIndex = 4;
this.buttonShowStorage.Text = "Посмотреть хранилище";
this.buttonShowStorage.UseVisualStyleBackColor = true;
this.buttonShowStorage.Click += new System.EventHandler(this.ButtonShowStorage_Click);
//
// buttonDown
//
this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDown.BackgroundImage = global::Stormtrooper.Properties.Resources.arrowDown;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonDown.Location = new System.Drawing.Point(104, 672);
this.buttonDown.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(34, 40);
this.buttonDown.TabIndex = 10;
this.buttonDown.UseVisualStyleBackColor = true;
this.buttonDown.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonRight
//
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::Stormtrooper.Properties.Resources.arrowRight;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonRight.Location = new System.Drawing.Point(145, 672);
this.buttonRight.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(34, 40);
this.buttonRight.TabIndex = 9;
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::Stormtrooper.Properties.Resources.arrowLeft;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonLeft.Location = new System.Drawing.Point(63, 672);
this.buttonLeft.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(34, 40);
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::Stormtrooper.Properties.Resources.arrowUp;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonUp.Location = new System.Drawing.Point(104, 624);
this.buttonUp.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(34, 40);
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, 521);
this.buttonShowOnMap.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonShowOnMap.Name = "buttonShowOnMap";
this.buttonShowOnMap.Size = new System.Drawing.Size(200, 47);
this.buttonShowOnMap.TabIndex = 5;
this.buttonShowOnMap.Text = "Посмотреть карту";
this.buttonShowOnMap.UseVisualStyleBackColor = true;
this.buttonShowOnMap.Click += new System.EventHandler(this.ButtonShowOnMap_Click);
//
// buttonAddStorm
//
this.buttonAddStorm.Location = new System.Drawing.Point(19, 141);
this.buttonAddStorm.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonAddStorm.Name = "buttonAddStorm";
this.buttonAddStorm.Size = new System.Drawing.Size(200, 47);
this.buttonAddStorm.TabIndex = 1;
this.buttonAddStorm.Text = "Добавить самолёт";
this.buttonAddStorm.UseVisualStyleBackColor = true;
this.buttonAddStorm.Click += new System.EventHandler(this.ButtonAddStorm_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, 43);
this.comboBoxSelectorMap.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.comboBoxSelectorMap.Name = "comboBoxSelectorMap";
this.comboBoxSelectorMap.Size = new System.Drawing.Size(199, 28);
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.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.pictureBox.Name = "pictureBox";
this.pictureBox.Size = new System.Drawing.Size(927, 739);
this.pictureBox.TabIndex = 1;
this.pictureBox.TabStop = false;
//
// FormMapWithSetStormtroopers
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1160, 739);
this.Controls.Add(this.pictureBox);
this.Controls.Add(this.groupBoxTools);
this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.Name = "FormMapWithSetStormtroopers";
this.Text = "Карта с набором объектов";
this.groupBoxTools.ResumeLayout(false);
this.groupBoxTools.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
this.ResumeLayout(false);
}
#endregion
private GroupBox groupBoxTools;
private PictureBox pictureBox;
private ComboBox comboBoxSelectorMap;
private Button buttonShowOnMap;
private Button buttonAddStorm;
private Button buttonDown;
private Button buttonRight;
private Button buttonLeft;
private Button buttonUp;
private Button buttonShowStorage;
private Button buttonRemoveStorm;
private MaskedTextBox maskedTextBoxPosition;
}
}

View File

@ -0,0 +1,166 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Stormtrooper
{
public partial class FormMapWithSetStormtroopers : Form
{
/// <summary>
/// Объект от класса карты с набором объектов
/// </summary>
private MapWithSetStormtroopersGeneric<DrawningObjectStorm, AbstractMap> _mapStormtroopersCollectionGeneric;
/// <summary>
/// Конструктор
/// </summary>
public FormMapWithSetStormtroopers()
{
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 SecondMap();
break;
case "Пасмурное небо":
map = new ThirdMap();
break;
}
if (map != null)
{
_mapStormtroopersCollectionGeneric = new MapWithSetStormtroopersGeneric<DrawningObjectStorm, AbstractMap>(
pictureBox.Width, pictureBox.Height, map);
}
else
{
_mapStormtroopersCollectionGeneric = null;
}
}
/// <summary>
/// Добавление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonAddStorm_Click(object sender, EventArgs e)
{
if (_mapStormtroopersCollectionGeneric == null)
{
return;
}
FormStormtrooper form = new();
if (form.ShowDialog() == DialogResult.OK)
{
DrawningObjectStorm car = new(form.SelectedStormtrooper);
if ((_mapStormtroopersCollectionGeneric + car) != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _mapStormtroopersCollectionGeneric.ShowSet();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
}
/// <summary>
/// Удаление объекта
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonRemoveStorm_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 ((_mapStormtroopersCollectionGeneric - pos) != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _mapStormtroopersCollectionGeneric.ShowSet();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
/// <summary>
/// Вывод набора
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonShowStorage_Click(object sender, EventArgs e)
{
if (_mapStormtroopersCollectionGeneric == null)
{
return;
}
pictureBox.Image = _mapStormtroopersCollectionGeneric.ShowSet();
}
/// <summary>
/// Вывод карты
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonShowOnMap_Click(object sender, EventArgs e)
{
if (_mapStormtroopersCollectionGeneric == null)
{
return;
}
pictureBox.Image = _mapStormtroopersCollectionGeneric.ShowOnMap();
}
/// <summary>
/// Перемещение
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonMove_Click(object sender, EventArgs e)
{
if (_mapStormtroopersCollectionGeneric == 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 = _mapStormtroopersCollectionGeneric.MoveObject(dir);
}
}
}

View File

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

View File

@ -38,6 +38,8 @@
this.buttonLeft = new System.Windows.Forms.Button();
this.buttonDown = new System.Windows.Forms.Button();
this.buttonUp = new System.Windows.Forms.Button();
this.buttonCreateModif = new System.Windows.Forms.Button();
this.buttonSelectStorm = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxStormtrooper)).BeginInit();
this.statusStrip1.SuspendLayout();
this.SuspendLayout();
@ -147,11 +149,34 @@
this.buttonUp.UseVisualStyleBackColor = true;
this.buttonUp.Click += new System.EventHandler(this.ButtonMove_Click);
//
// buttonCreateModif
//
this.buttonCreateModif.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonCreateModif.Location = new System.Drawing.Point(125, 396);
this.buttonCreateModif.Name = "buttonCreateModif";
this.buttonCreateModif.Size = new System.Drawing.Size(120, 29);
this.buttonCreateModif.TabIndex = 7;
this.buttonCreateModif.Text = "Модификация";
this.buttonCreateModif.UseVisualStyleBackColor = true;
this.buttonCreateModif.Click += new System.EventHandler(this.ButtonCreateModif_Click);
//
// buttonSelectStorm
//
this.buttonSelectStorm.Location = new System.Drawing.Point(260, 396);
this.buttonSelectStorm.Name = "buttonSelectStorm";
this.buttonSelectStorm.Size = new System.Drawing.Size(94, 29);
this.buttonSelectStorm.TabIndex = 8;
this.buttonSelectStorm.Text = "Выбрать";
this.buttonSelectStorm.UseVisualStyleBackColor = true;
this.buttonSelectStorm.Click += new System.EventHandler(this.ButtonSelectStorm_Click);
//
// FormStormtrooper
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(831, 461);
this.Controls.Add(this.buttonSelectStorm);
this.Controls.Add(this.buttonCreateModif);
this.Controls.Add(this.buttonUp);
this.Controls.Add(this.buttonDown);
this.Controls.Add(this.buttonLeft);
@ -181,5 +206,7 @@
private Button buttonLeft;
private Button buttonDown;
private Button buttonUp;
private Button buttonCreateModif;
private Button buttonSelectStorm;
}
}

View File

@ -3,12 +3,16 @@ namespace Stormtrooper
public partial class FormStormtrooper : Form
{
private Drawning _storm;
/// <summary>
/// Âûáðàííûé îáúåêò
/// </summary>
public Drawning SelectedStormtrooper { get; private set; }
public FormStormtrooper()
{
InitializeComponent();
}
//private EntityStormtrooper Storm;
/// <summary>
/// Ìåòîä ïðîðèñîâêè ñàìîë¸òà
/// </summary>
@ -19,6 +23,18 @@ namespace Stormtrooper
_storm?.DrawTransport(gr);
pictureBoxStormtrooper.Image = bmp;
}
/// <summary>
/// Ìåòîä óñòàíîâêè äàííûõ
/// </summary>
private void SetData()
{
Random rnd = new();
_storm.SetPosition(rnd.Next(0, 150), rnd.Next(0, 300), pictureBoxStormtrooper.Width, pictureBoxStormtrooper.Height);
toolStripStatusLabelSpeed.Text = $"Ñêîðîñòü: {_storm.Storm.Speed}";
toolStripStatusLabelWeight.Text = $"Âåñ: {_storm.Storm.Weight}";
toolStripStatusLabelColor.Text = $"Öâåò: {_storm.Storm.BodyColor.Name}";
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ñîçäàòü"
/// </summary>
@ -27,12 +43,14 @@ namespace Stormtrooper
private void ButtonCreate_Click(object sender, EventArgs e)
{
Random rnd = new();
_storm = new Drawning();
_storm.Init(rnd.Next(100,300), rnd.Next(1000,2000), Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256)));
_storm.SetPosition(rnd.Next(0, 150), rnd.Next(0, 300), pictureBoxStormtrooper.Width, pictureBoxStormtrooper.Height);
toolStripStatusLabelSpeed.Text = $"Ñêîðîñòü: {_storm.Storm.Speed}";
toolStripStatusLabelWeight.Text = $"Âåñ: {_storm.Storm.Weight}";
toolStripStatusLabelColor.Text = $"Öâåò: {_storm.Storm.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;
}
_storm = new Drawning(rnd.Next(100, 300), rnd.Next(1000, 2000), color);
SetData();
Draw();
}
/// <summary>
@ -71,5 +89,27 @@ namespace Stormtrooper
_storm?.ChangeBorders(pictureBoxStormtrooper.Width, pictureBoxStormtrooper.Height);
Draw();
}
/// <summary>
/// Îáðàáîòêà íàæàòèÿ êíîïêè "Ìîäèôèêàöèÿ"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateModif_Click(object sender, EventArgs e)
{
Random rnd = new();
_storm = new DrawningMilitary(rnd.Next(100, 300), rnd.Next(1000, 2000),
Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256)),
Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256)),
Convert.ToBoolean(rnd.Next(0, 2)), Convert.ToBoolean(rnd.Next(0, 2)), Convert.ToBoolean(rnd.Next(0, 2)));
SetData();
Draw();
}
private void ButtonSelectStorm_Click(object sender, EventArgs e)
{
SelectedStormtrooper = _storm;
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 Stormtrooper
{
/// <summary>
/// Интерфейс для работы с объектом, прорисовываемым на форме
/// </summary>
internal interface IDrawningObject
{
/// <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>
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,186 @@
using System;
using System.Collections.Generic;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Stormtrooper
{
/// <summary>
/// Карта с набром объектов под нее
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
internal class MapWithSetStormtroopersGeneric<T, U>
where T : class, IDrawningObject
where U : AbstractMap
{
/// <summary>
/// Ширина окна отрисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна отрисовки
/// </summary>
private readonly int _pictureHeight;
/// <summary>
/// Размер занимаемого объектом места (ширина)
/// </summary>
private readonly int _placeSizeWidth = 135;
/// <summary>
/// Размер занимаемого объектом места (высота)
/// </summary>
private readonly int _placeSizeHeight = 100;
/// <summary>
/// Набор объектов
/// </summary>
private readonly SetStormtroopersGeneric<T> _setStormtroopers;
/// <summary>
/// Карта
/// </summary>
private readonly U _map;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="picWidth"></param>
/// <param name="picHeight"></param>
/// <param name="map"></param>
public MapWithSetStormtroopersGeneric(int picWidth, int picHeight, U map)
{
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_map = map;
_setStormtroopers = new SetStormtroopersGeneric<T>(width * height);
}
/// <summary>
/// Перегрузка оператора сложения
/// </summary>
/// <param name="map"></param>
/// <param name="car"></param>
/// <returns></returns>
public static int operator +(MapWithSetStormtroopersGeneric<T, U> map, T stormtrooper)
{
return map._setStormtroopers.Insert(stormtrooper);
}
/// <summary>
/// Перегрузка оператора вычитания
/// </summary>
/// <param name="map"></param>
/// <param name="position"></param>
/// <returns></returns>
public static T operator -(MapWithSetStormtroopersGeneric<T, U> map, int
position)
{
return map._setStormtroopers.Remove(position);
}
/// <summary>
/// Вывод всего набора объектов
/// </summary>
/// <returns></returns>
public Bitmap ShowSet()
{
Bitmap bmp = new(_pictureWidth, _pictureHeight);
Graphics gr = Graphics.FromImage(bmp);
DrawBackground(gr);
DrawStormtroopers(gr);
return bmp;
}
/// <summary>
/// Просмотр объекта на карте
/// </summary>
/// <returns></returns>
public Bitmap ShowOnMap()
{
Shaking();
for (int i = 0; i < _setStormtroopers.Count; i++)
{
var car = _setStormtroopers.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 = _setStormtroopers.Count - 1;
for (int i = 0; i < _setStormtroopers.Count; i++)
{
if (_setStormtroopers.Get(i) == null)
{
for (; j > i; j--)
{
var car = _setStormtroopers.Get(j);
if (car != null)
{
_setStormtroopers.Insert(car, i);
_setStormtroopers.Remove(j);
break;
}
}
if (j <= i)
{
return;
}
}
}
}
/// <summary>
/// Метод отрисовки фона
/// </summary>
/// <param name="g"></param>
private void DrawBackground(Graphics g)
{
Brush br = new SolidBrush(Color.Gray);
g.FillRectangle(br, new Rectangle(0, 0, _pictureWidth, _pictureHeight));
Pen pen = new(Color.White, 3);
pen.DashStyle = DashStyle.Dash;
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.DrawLine(pen, i * _placeSizeWidth, 0, i * _placeSizeWidth,
(_pictureHeight / _placeSizeHeight) * _placeSizeHeight);
}
}
/// <summary>
/// Метод прорисовки объектов
/// </summary>
/// <param name="g"></param>
private void DrawStormtroopers(Graphics g)
{
int numOfObjectsInRow = _pictureWidth / _placeSizeWidth;
int i = 0;
for (int j = 0; j < _setStormtroopers.Count; j++)
{
_setStormtroopers.Get(i)?.SetObject((numOfObjectsInRow - (i % numOfObjectsInRow) - 1) * _placeSizeWidth, (i / numOfObjectsInRow) * _placeSizeHeight + _placeSizeHeight, _pictureWidth, _pictureHeight);
_setStormtroopers.Get(i)?.DrawningObject(g);
i++;
}
}
}
}

View File

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

View File

@ -0,0 +1,52 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Stormtrooper
{
internal class SecondMap:AbstractMap
{
/// <summary>
/// Цвет участка закрытого
/// </summary>
private readonly Brush barrierColor = new SolidBrush(Color.White);
/// <summary>
/// Цвет участка открытого
/// </summary>
private readonly Brush roadColor = new SolidBrush(Color.LightBlue);
protected override void DrawBarrierPart(Graphics g, int i, int j)
{
g.FillEllipse(barrierColor, i * _size_x, j * _size_y, _size_x+3, _size_y+3);
}
protected override void DrawRoadPart(Graphics g, int i, int j)
{
g.FillRectangle(roadColor, 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;
}
}
while (counter < 30)
{
int x = _random.Next(0, 100);
int y = _random.Next(0, 100);
if (_map[x, y] == _freeRoad)
{
_map[x, y] = _barrier;
counter++;
}
}
}
}
}

View File

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

View File

@ -0,0 +1,52 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Stormtrooper
{
internal class SimpleMap : AbstractMap
{
/// <summary>
/// Цвет участка закрытого
/// </summary>
private readonly Brush barrierColor = new SolidBrush(Color.Black);
/// <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, _size_x, _size_y);
}
protected override void DrawRoadPart(Graphics g, int i, int j)
{
g.FillRectangle(roadColor, 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;
}
}
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++;
}
}
}
}
}

View File

@ -0,0 +1,69 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Stormtrooper
{
internal class ThirdMap:AbstractMap
{
/// <summary>
/// Цвет участка закрытого
/// </summary>
private readonly Brush barrierColor = new SolidBrush(Color.Gray);
/// <summary>
/// Цвет участка открытого
/// </summary>
private readonly Brush roadColor = new SolidBrush(Color.LightGray);
protected override void DrawBarrierPart(Graphics g, int i, int j)
{
g.FillEllipse(barrierColor, i * _size_x, j * _size_y, _size_x + 3, _size_y + 3);
}
protected override void DrawRoadPart(Graphics g, int i, int j)
{
g.FillRectangle(roadColor, 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;
}
}
while (counter < 30)
{
int x = _random.Next(0, 30);
int y = _random.Next(0, 30);
if (_map[x, y] == _freeRoad)
{
_map[x, y] = _barrier;
counter++;
}
x = _random.Next(70, 100);
y = _random.Next(0, 30);
if (_map[x, y] == _freeRoad)
{
_map[x, y] = _barrier;
counter++;
}
x = _random.Next(40, 60);
y = _random.Next(50, 90);
if (_map[x, y] == _freeRoad)
{
_map[x, y] = _barrier;
counter++;
}
}
}
}
}