Compare commits

...

11 Commits

Author SHA1 Message Date
nikbel2004@outlook.com
b3d0980f05 Готовая лаба 3 2023-10-28 20:06:01 +04:00
nikbel2004@outlook.com
c69b8824c6 Готовая лабораторная 3 2023-10-21 16:09:16 +04:00
nikbel2004@outlook.com
b54059d598 Правки в лабораторной 3 2023-10-21 14:36:51 +04:00
nikbel2004@outlook.com
a17318de92 Лабораторная 3 2023-10-21 14:19:42 +04:00
nikbel2004@outlook.com
af6582be5e Правки лабораторная 2 2023-10-08 00:32:32 +04:00
nikbel2004@outlook.com
62e9cfef11 Правки лабораторная 2 2023-10-08 00:30:07 +04:00
nikbel2004@outlook.com
37572c6e3c Правки лабораторная 2 2023-10-08 00:16:27 +04:00
nikbel2004@outlook.com
21ce7abbe3 Правки в лабораторной 2 2023-10-08 00:14:56 +04:00
nikbel2004@outlook.com
e0874c2924 Лабораторная 2 2023-10-04 03:06:05 +04:00
nikbel2004@outlook.com
72a71f346b Готовая 1 лаба 2023-09-13 17:11:16 +04:00
nikbel2004@outlook.com
ce4b2141be Создание проекта 2023-09-13 16:48:27 +04:00
29 changed files with 1782 additions and 0 deletions

25
Tank/Tank.sln Normal file
View File

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.7.34031.279
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tank", "Tank\Tank.csproj", "{5C602C58-ECEC-4FAB-BA10-FB671582D227}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{5C602C58-ECEC-4FAB-BA10-FB671582D227}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5C602C58-ECEC-4FAB-BA10-FB671582D227}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5C602C58-ECEC-4FAB-BA10-FB671582D227}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5C602C58-ECEC-4FAB-BA10-FB671582D227}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {73BF3262-E499-401F-BDBD-BD2BC7D3C324}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,73 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tank.MovementStrategy
{
public abstract class AbstractStrategy
{
private IMoveableObject? _moveableObject;
private Status _state = Status.NotInit;
protected int FieldWidth { get; private set; }
protected int FieldHeight { get; private set; }
public Status GetStatus() { return _state; }
public void SetData(IMoveableObject moveableObject, int width, int height)
{
if (moveableObject == null)
{
_state = Status.NotInit;
return;
}
_state = Status.InProgress;
_moveableObject = moveableObject;
FieldHeight = height;
FieldWidth = width;
}
public void MakeStep()
{
if (_state != Status.InProgress)
return;
if (IsTargetDestination())
{
_state = Status.Finish;
return;
}
MoveToTarget();
}
protected bool MoveLeft() => MoveTo(Direction.Left);
protected bool MoveRight() => MoveTo(Direction.Right);
protected bool MoveUp() => MoveTo(Direction.Up);
protected bool MoveDown() => MoveTo(Direction.Down);
protected ObjectParameters? GetObjectParameters => _moveableObject?.GetObjectParameters;
protected int? GetStep()
{
if (_state != Status.InProgress)
{
return null;
}
return _moveableObject?.GetStep;
}
protected abstract void MoveToTarget();
protected abstract bool IsTargetDestination();
private bool MoveTo(Direction direction)
{
if (_state != Status.InProgress)
return false;
if (_moveableObject?.CheckCanMove(direction) ?? false)
{
_moveableObject.MoveObject(direction);
return true;
}
return false;
}
}
}

16
Tank/Tank/Direction.cs Normal file
View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tank
{
public enum Direction
{
Up = 1,
Down = 2,
Left = 3,
Right = 4
}
}

View File

@ -0,0 +1,131 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.Pkcs;
using System.Text;
using System.Threading.Tasks;
using Tank.Entities;
using Tank.MovementStrategy;
namespace Tank
{
public class DrawArmoVehicle
{
public EntityArmoVehicle? Tank { get; protected set; }
protected int _pictureWidth;
protected int _pictureHeight;
protected int _startPosX;
protected int _startPosY;
protected readonly int _Width = 160;
protected readonly int _Height = 90;
public int GetPosX => _startPosX;
public int GetPosY => _startPosY;
public int GetWidth => _Width;
public int GetHeight => _Height;
// Конструктор класса
public DrawArmoVehicle(int speed, double weight, Color bodyColor, int width, int height)
{
_pictureHeight = height;
_pictureWidth = width;
if (_pictureHeight < _Height || _pictureWidth < _Width)
return;
Tank = new EntityArmoVehicle(speed, weight, bodyColor);
}
protected DrawArmoVehicle(int speed, double weight, Color bodyColor, int width, int height, int tankWidth, int tankHeight)
{
_pictureHeight = height;
_pictureWidth = width;
_Height = tankHeight;
_Width = tankWidth;
if (_pictureHeight < _Height || _pictureWidth < _Width)
return;
Tank = new EntityArmoVehicle(speed, weight, bodyColor);
}
public bool CanMove(Direction direction)
{
if (Tank == null)
return false;
return direction switch
{
Direction.Left => _startPosX - Tank.Step > 0,
Direction.Up => _startPosY - Tank.Step > 0,
Direction.Right => _startPosX + _Width + Tank.Step < _pictureWidth,
Direction.Down => _startPosY + _Height + Tank.Step < _pictureHeight,
_ => false
};
}
public void SetPosition(int x, int y)
{
_startPosX = x;
_startPosY = y;
}
public void MoveTransport(Direction direction)
{
if (!CanMove(direction) || Tank == null)
return;
switch (direction)
{
case Direction.Left:
{
if (_startPosX - Tank.Step > 0)
{
_startPosX -= (int)Tank.Step;
}
}
break;
case Direction.Up:
{
if (_startPosY - Tank.Step > 0)
{
_startPosY -= (int)Tank.Step;
}
}
break;
case Direction.Right:
{
if (_startPosX + _Width + Tank.Step < _pictureWidth)
{
_startPosX += (int)Tank.Step;
}
}
break;
case Direction.Down:
{
if (_startPosY + Tank.Step + _Height < _pictureHeight)
{
_startPosY += (int)Tank.Step;
}
}
break;
}
}
public virtual void DrawTransport(Graphics g)
{
if (Tank == null)
return;
Brush BrushRandom = new SolidBrush(Tank?.BodyColor ?? Color.Black);
//Корпус
Point[] pointsbody = { new Point(_startPosX + 5, _startPosY + 30), new Point(_startPosX + 110, _startPosY + 30),
new Point(_startPosX + 142, _startPosY + 30), new Point(_startPosX + 120, _startPosY + 45), new Point(_startPosX + 12, _startPosY + 45) };
g.FillPolygon(BrushRandom, pointsbody);
// Колеса, катки
Brush ColorBlack = new SolidBrush(Color.Black);
g.FillEllipse(ColorBlack, 10 + _startPosX, 42 + _startPosY, 20, 20);
g.FillEllipse(ColorBlack, 35 + _startPosX, 42 + _startPosY, 20, 20);
g.FillEllipse(ColorBlack, 60 + _startPosX, 42 + _startPosY, 20, 20);
g.FillEllipse(ColorBlack, 85 + _startPosX, 42 + _startPosY, 20, 20);
g.FillEllipse(ColorBlack, 110 + _startPosX, 42 + _startPosY, 20, 20);
}
public IMoveableObject GetMoveableObject => new DrawingObjectTank(this);
}
}

64
Tank/Tank/DrawTank.cs Normal file
View File

@ -0,0 +1,64 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tank.Entities;
namespace Tank.DrawningObjects
{
public class DrawTank : DrawArmoVehicle
{
public DrawTank(int speed, double weight, Color bodyColor, Color additionalColor, bool bodyKit, bool caterpillar, bool tower, int width, int height) : base(speed, weight, bodyColor, width, height)
{
if (Tank != null)
{
Tank = new EntityTank(speed, weight, bodyColor, additionalColor, bodyKit, caterpillar, tower);
}
}
public override void DrawTransport(Graphics g)
{
if (Tank is not EntityTank ArmoVehicle)
return;
base.DrawTransport(g);
if (ArmoVehicle.BodyKit)
{
Brush bodyBrush = new SolidBrush(ArmoVehicle.AdditionalColor);
// Корпус танка
Point[] pointtower = { new Point(_startPosX + 52, _startPosY + 30), new Point(_startPosX + 52, _startPosY + 27), new Point(_startPosX + 40, _startPosY + 23),
new Point(_startPosX + 15, _startPosY + 18), new Point(_startPosX + 15,_startPosY + 15), new Point(_startPosX + 60, _startPosY + 11), new Point(_startPosX + 90, _startPosY + 11),
new Point(_startPosX + 120, _startPosY + 20), new Point(_startPosX + 100,_startPosY + 25), new Point(_startPosX + 95, _startPosY + 27), new Point(_startPosX + 90, _startPosY + 30)};
g.FillPolygon(bodyBrush, pointtower);
}
if (ArmoVehicle.Caterpillar)
{
// Гусеница. Отрисовка танковых катков
Brush BrushRandom = new SolidBrush(Tank?.BodyColor ?? Color.Black);
g.FillRectangle(BrushRandom, 28 + _startPosX, 50 + _startPosY, 10, 3);
g.FillRectangle(BrushRandom, 53 + _startPosX, 50 + _startPosY, 10, 3);
g.FillRectangle(BrushRandom, 78 + _startPosX, 50 + _startPosY, 10, 3);
g.FillRectangle(BrushRandom, 103 + _startPosX, 50 + _startPosY, 10, 3);
}
if (ArmoVehicle.Tower)
{
// Орудие
Brush bodyBrush = new SolidBrush(ArmoVehicle.AdditionalColor);
g.FillRectangle(bodyBrush, _startPosX + 111, _startPosY + 17, 60, 5);
// Зенитное орудие
Point[] pointgun = { new Point(_startPosX + 44, _startPosY + 13), new Point(_startPosX + 45, _startPosY + 12), new Point(_startPosX + 41, _startPosY + 8), new Point(_startPosX + 41, _startPosY + 7),
new Point(_startPosX + 42, _startPosY + 5), new Point(_startPosX + 41, _startPosY + 4), new Point(_startPosX + 44, _startPosY + 3), new Point(_startPosX + 50, _startPosY + 3),
new Point(_startPosX + 52, _startPosY + 5), new Point(_startPosX + 53, _startPosY + 7), new Point(_startPosX + 58, _startPosY + 11)};
g.FillPolygon(bodyBrush, pointgun);
g.FillRectangle(bodyBrush, _startPosX + 50, _startPosY + 5, 20, 2);
}
}
}
}

View File

@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tank.DrawningObjects;
namespace Tank.MovementStrategy
{
public class DrawingObjectTank : IMoveableObject
{
private readonly DrawArmoVehicle? _drawTank = null;
public DrawingObjectTank(DrawArmoVehicle drawTank)
{
_drawTank = drawTank;
}
public ObjectParameters? GetObjectParameters
{
get
{
if (_drawTank == null || _drawTank.Tank == null)
return null;
return new ObjectParameters(_drawTank.GetPosX, _drawTank.GetPosY, _drawTank.GetWidth, _drawTank.GetHeight);
}
}
public int GetStep => (int)(_drawTank?.Tank?.Step ?? 0);
public bool CheckCanMove(Direction direction) => _drawTank?.CanMove(direction) ?? false;
public void MoveObject(Direction direction) => _drawTank?.MoveTransport(direction);
}
}

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tank.Entities
{
public class EntityArmoVehicle
{
public int Speed { get; private set; }
public double Weight { get; private set; }
public Color BodyColor { get; private set; }
public double Step => (double)Speed * 100 / Weight;
public EntityArmoVehicle(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
}
}
}

23
Tank/Tank/EntityTank.cs Normal file
View File

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tank.Entities
{
public class EntityTank : EntityArmoVehicle
{
public Color AdditionalColor { get; private set; }
public bool BodyKit { get; private set; }
public bool Caterpillar { get; private set; }
public bool Tower { get; private set; }
public EntityTank(int speed, double weight, Color bodyColor, Color additionalColor, bool bodyKit, bool caterpillar, bool tower) : base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
BodyKit = bodyKit;
Caterpillar = caterpillar;
Tower = tower;
}
}
}

193
Tank/Tank/FormTank.Designer.cs generated Normal file
View File

@ -0,0 +1,193 @@
namespace Tank
{
partial class FormTank
{
/// <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()
{
pictureBoxTank = new PictureBox();
ButtonCreate = new Button();
keyDown = new Button();
keyUp = new Button();
keyLeft = new Button();
keyRight = new Button();
buttonArmVechicle = new Button();
buttonStep = new Button();
comboBoxStrategy = new ComboBox();
ChooseCar = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxTank).BeginInit();
SuspendLayout();
//
// pictureBoxTank
//
pictureBoxTank.Location = new Point(1, 0);
pictureBoxTank.Margin = new Padding(3, 4, 3, 4);
pictureBoxTank.Name = "pictureBoxTank";
pictureBoxTank.Size = new Size(913, 571);
pictureBoxTank.TabIndex = 0;
pictureBoxTank.TabStop = false;
//
// ButtonCreate
//
ButtonCreate.Location = new Point(14, 500);
ButtonCreate.Margin = new Padding(3, 4, 3, 4);
ButtonCreate.Name = "ButtonCreate";
ButtonCreate.Size = new Size(145, 53);
ButtonCreate.TabIndex = 1;
ButtonCreate.Text = "Создание танка";
ButtonCreate.UseVisualStyleBackColor = true;
ButtonCreate.Click += ButtonCreateTank_Click;
//
// keyDown
//
keyDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
keyDown.BackgroundImage = Properties.Resources.KeyDown;
keyDown.BackgroundImageLayout = ImageLayout.Stretch;
keyDown.Location = new Point(821, 515);
keyDown.Margin = new Padding(3, 4, 3, 4);
keyDown.Name = "keyDown";
keyDown.Size = new Size(34, 40);
keyDown.TabIndex = 11;
keyDown.UseVisualStyleBackColor = true;
keyDown.Click += ButtonMove_Click;
//
// keyUp
//
keyUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
keyUp.BackgroundImage = Properties.Resources.KeyUp;
keyUp.BackgroundImageLayout = ImageLayout.Stretch;
keyUp.Location = new Point(821, 467);
keyUp.Margin = new Padding(3, 4, 3, 4);
keyUp.Name = "keyUp";
keyUp.Size = new Size(34, 40);
keyUp.TabIndex = 12;
keyUp.UseVisualStyleBackColor = true;
keyUp.Click += ButtonMove_Click;
//
// keyLeft
//
keyLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
keyLeft.BackgroundImage = Properties.Resources.KeyLeft;
keyLeft.BackgroundImageLayout = ImageLayout.Stretch;
keyLeft.Location = new Point(779, 515);
keyLeft.Margin = new Padding(3, 4, 3, 4);
keyLeft.Name = "keyLeft";
keyLeft.Size = new Size(34, 40);
keyLeft.TabIndex = 13;
keyLeft.UseVisualStyleBackColor = true;
keyLeft.Click += ButtonMove_Click;
//
// keyRight
//
keyRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
keyRight.BackgroundImage = Properties.Resources.KeyRight;
keyRight.BackgroundImageLayout = ImageLayout.Stretch;
keyRight.Location = new Point(861, 515);
keyRight.Margin = new Padding(3, 4, 3, 4);
keyRight.Name = "keyRight";
keyRight.Size = new Size(34, 40);
keyRight.TabIndex = 14;
keyRight.UseVisualStyleBackColor = true;
keyRight.Click += ButtonMove_Click;
//
// buttonArmVechicle
//
buttonArmVechicle.Location = new Point(176, 501);
buttonArmVechicle.Margin = new Padding(3, 4, 3, 4);
buttonArmVechicle.Name = "buttonArmVechicle";
buttonArmVechicle.Size = new Size(150, 53);
buttonArmVechicle.TabIndex = 15;
buttonArmVechicle.Text = "Создание бронеавтомобиля";
buttonArmVechicle.UseVisualStyleBackColor = true;
buttonArmVechicle.Click += CreateButtonArmoVehicle_Click;
//
// buttonStep
//
buttonStep.Location = new Point(815, 71);
buttonStep.Margin = new Padding(3, 4, 3, 4);
buttonStep.Name = "buttonStep";
buttonStep.Size = new Size(86, 31);
buttonStep.TabIndex = 17;
buttonStep.Text = "Шаг";
buttonStep.UseVisualStyleBackColor = true;
buttonStep.Click += ButtonStep_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "0", "1" });
comboBoxStrategy.Location = new Point(749, 24);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(151, 28);
comboBoxStrategy.TabIndex = 19;
//
// ChooseCar
//
ChooseCar.Location = new Point(807, 120);
ChooseCar.Name = "ChooseCar";
ChooseCar.Size = new Size(94, 52);
ChooseCar.TabIndex = 20;
ChooseCar.Text = "Выбрать технику";
ChooseCar.UseVisualStyleBackColor = true;
ChooseCar.Click += ButtonSelectTank_Click;
//
// FormTank
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
BackColor = SystemColors.ButtonHighlight;
ClientSize = new Size(914, 568);
Controls.Add(ChooseCar);
Controls.Add(comboBoxStrategy);
Controls.Add(buttonStep);
Controls.Add(buttonArmVechicle);
Controls.Add(keyRight);
Controls.Add(keyLeft);
Controls.Add(keyUp);
Controls.Add(keyDown);
Controls.Add(ButtonCreate);
Controls.Add(pictureBoxTank);
Margin = new Padding(3, 4, 3, 4);
Name = "FormTank";
Text = "FormTank";
((System.ComponentModel.ISupportInitialize)pictureBoxTank).EndInit();
ResumeLayout(false);
}
#endregion
private PictureBox pictureBoxTank;
private Button ButtonCreate;
private Button keyRight;
private Button keyLeft;
private Button keyUp;
private Button keyDown;
private Button buttonArmVechicle;
private Button buttonStep;
private ComboBox comboBoxStrategy;
private Button ChooseCar;
}
}

132
Tank/Tank/FormTank.cs Normal file
View File

@ -0,0 +1,132 @@
using Tank.DrawningObjects;
using Tank.MovementStrategy;
namespace Tank
{
public partial class FormTank : Form
{
private DrawArmoVehicle? _Tank;
private AbstractStrategy? _abstractStrategy;
public DrawArmoVehicle? SelectedTank { get; private set; }
public FormTank()
{
InitializeComponent();
_abstractStrategy = null;
SelectedTank = null;
}
private void Draw()
{
if (_Tank == null)
return;
Bitmap bitmap = new(pictureBoxTank.Width, pictureBoxTank.Height);
Graphics gr = Graphics.FromImage(bitmap);
_Tank?.DrawTransport(gr);
pictureBoxTank.Image = bitmap;
}
private void ButtonCreateTank_Click(object sender, EventArgs e)
{
Random rnd = new();
Color mainColor = Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256));
ColorDialog dialog = new();
if (dialog.ShowDialog() == DialogResult.OK)
{
mainColor = dialog.Color;
}
Color addColor = Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256));
if (dialog.ShowDialog() == DialogResult.OK)
{
addColor = dialog.Color;
}
_Tank = new DrawTank(rnd.Next(100, 200), rnd.Next(2000, 4000),
mainColor, addColor,
Convert.ToBoolean(rnd.Next(1, 2)), Convert.ToBoolean(rnd.Next(1, 2)), Convert.ToBoolean(rnd.Next(1, 2)),
pictureBoxTank.Width, pictureBoxTank.Height);
_Tank.SetPosition(rnd.Next(10, 100), rnd.Next(10, 100));
Draw();
}
private void ButtonMove_Click(object sender, EventArgs e)
{
//ïîëó÷àåì èìÿ êíîïêè
if (_Tank == null)
return;
string name = ((Button)sender)?.Name ?? string.Empty;
switch (name)
{
case "keyUp":
_Tank?.MoveTransport(Direction.Up);
break;
case "keyDown":
_Tank?.MoveTransport(Direction.Down);
break;
case "keyLeft":
_Tank?.MoveTransport(Direction.Left);
break;
case "keyRight":
_Tank?.MoveTransport(Direction.Right);
break;
}
Draw();
}
private void CreateButtonArmoVehicle_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;
}
_Tank = new DrawArmoVehicle(rnd.Next(100, 200), rnd.Next(2000, 4000),
color, pictureBoxTank.Width, pictureBoxTank.Height);
_Tank.SetPosition(rnd.Next(10, 50), rnd.Next(30, 70));
Draw();
}
private void ButtonStep_Click(object sender, EventArgs e)
{
if (_Tank == null)
return;
if (comboBoxStrategy.Enabled)
{
_abstractStrategy = comboBoxStrategy.SelectedIndex switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null
};
if (_abstractStrategy == null)
return;
_abstractStrategy.SetData(new DrawingObjectTank(_Tank), pictureBoxTank.Width, pictureBoxTank.Height);
comboBoxStrategy.Enabled = false;
}
if (_abstractStrategy == null)
return;
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_abstractStrategy = null;
}
}
private void ButtonSelectTank_Click(object sender, EventArgs e)
{
SelectedTank = _Tank;
DialogResult = DialogResult.OK;
}
}
}

120
Tank/Tank/FormTank.resx Normal file
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>

135
Tank/Tank/FormTanksCollections.Designer.cs generated Normal file
View File

@ -0,0 +1,135 @@
namespace Tank
{
partial class FormTanksCollections
{
/// <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()
{
panel1 = new Panel();
UpdateButton = new Button();
DeleteButton = new Button();
AddButton = new Button();
InputNum = new TextBox();
label1 = new Label();
DrawTank = new PictureBox();
panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)DrawTank).BeginInit();
SuspendLayout();
//
// panel1
//
panel1.Controls.Add(UpdateButton);
panel1.Controls.Add(DeleteButton);
panel1.Controls.Add(AddButton);
panel1.Controls.Add(InputNum);
panel1.Controls.Add(label1);
panel1.Dock = DockStyle.Right;
panel1.Location = new Point(550, 0);
panel1.Name = "panel1";
panel1.Size = new Size(250, 451);
panel1.TabIndex = 0;
//
// UpdateButton
//
UpdateButton.Location = new Point(10, 241);
UpdateButton.Name = "UpdateButton";
UpdateButton.Size = new Size(229, 37);
UpdateButton.TabIndex = 4;
UpdateButton.Text = "Обновить коллекцию";
UpdateButton.UseVisualStyleBackColor = true;
UpdateButton.Click += ButtonRefreshCollection_Click;
//
// DeleteButton
//
DeleteButton.Location = new Point(10, 176);
DeleteButton.Name = "DeleteButton";
DeleteButton.Size = new Size(229, 37);
DeleteButton.TabIndex = 3;
DeleteButton.Text = "Удалить технику";
DeleteButton.UseVisualStyleBackColor = true;
DeleteButton.Click += ButtonRemoveTank_Click;
//
// AddButton
//
AddButton.Location = new Point(10, 53);
AddButton.Name = "AddButton";
AddButton.Size = new Size(229, 37);
AddButton.TabIndex = 2;
AddButton.Text = "Добавить технику";
AddButton.UseVisualStyleBackColor = true;
AddButton.Click += ButtonAddTank_Click;
//
// InputNum
//
InputNum.Location = new Point(10, 133);
InputNum.Name = "InputNum";
InputNum.Size = new Size(228, 27);
InputNum.TabIndex = 1;
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(2, 3);
label1.Name = "label1";
label1.Size = new Size(103, 20);
label1.TabIndex = 0;
label1.Text = "Инструменты";
//
// DrawTank
//
DrawTank.Dock = DockStyle.Fill;
DrawTank.Location = new Point(0, 0);
DrawTank.Name = "DrawTank";
DrawTank.Size = new Size(550, 451);
DrawTank.TabIndex = 1;
DrawTank.TabStop = false;
//
// CollectionsFrame
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 451);
Controls.Add(DrawTank);
Controls.Add(panel1);
Name = "CollectionsFrame";
Text = "CollectionsFrame";
panel1.ResumeLayout(false);
panel1.PerformLayout();
((System.ComponentModel.ISupportInitialize)DrawTank).EndInit();
ResumeLayout(false);
}
#endregion
private Panel panel1;
private Button UpdateButton;
private Button DeleteButton;
private Button AddButton;
private TextBox InputNum;
private Label label1;
private PictureBox DrawTank;
}
}

View File

@ -0,0 +1,71 @@
using Tank.DrawningObjects;
using Tank.Generics;
using Tank.MovementStrategy;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Tank
{
public partial class FormTanksCollections : Form
{
private readonly TanksGenericCollection<DrawArmoVehicle, DrawingObjectTank> _tanks;
public FormTanksCollections()
{
InitializeComponent();
_tanks = new TanksGenericCollection<DrawArmoVehicle, DrawingObjectTank>(DrawTank.Width, DrawTank.Height);
}
private void ButtonAddTank_Click(object sender, EventArgs e)
{
FormTank form = new FormTank();
if (form.ShowDialog() == DialogResult.OK)
{
if (_tanks + form.SelectedTank != -1)
{
MessageBox.Show("Объект добавлен");
DrawTank.Image = _tanks.ShowTanks();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
}
private void ButtonRemoveTank_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = -1;
try
{
pos = Convert.ToInt32(InputNum.Text);
}
catch (Exception ex) { }
if (_tanks - pos)
{
MessageBox.Show("Объект удален");
DrawTank.Image = _tanks.ShowTanks();
}
else
{
MessageBox.Show("Не удалось удалить объект");
}
}
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
{
DrawTank.Image = _tanks.ShowTanks();
}
}
}

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

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tank.MovementStrategy
{
public interface IMoveableObject
{
ObjectParameters? GetObjectParameters { get; }
int GetStep { get; }
bool CheckCanMove(Direction direction);
void MoveObject(Direction direction);
}
}

47
Tank/Tank/MoveToBorder.cs Normal file
View File

@ -0,0 +1,47 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tank.MovementStrategy
{
public class MoveToBorder : AbstractStrategy
{
protected override bool IsTargetDestination()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return false;
}
return objParams.RightBorder + GetStep() >= FieldWidth && objParams.DownBorder + GetStep() >= FieldHeight;
}
protected override void MoveToTarget()
{
var objParams = GetObjectParameters;
if (objParams == null)
{
return;
}
var diffX = objParams.RightBorder - FieldWidth;
var diffY = objParams.DownBorder - FieldHeight;
if (diffX >= 0)
{
MoveDown();
}
else if (diffY >= 0)
{
MoveRight();
}
else if (Math.Abs(diffX) > Math.Abs(diffY))
{
MoveRight();
}
else
{
MoveDown();
}
}
}
}

54
Tank/Tank/MoveToCenter.cs Normal file
View File

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

View File

@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tank.MovementStrategy
{
public class ObjectParameters
{
private readonly int _x;
private readonly int _y;
private readonly int _width;
private readonly int _height;
public int LeftBorder => _x; // Левая граница
public int TopBorder => _y; // Верхняя граница
public int RightBorder => _width + _x; // Правая граница
public int DownBorder => _height + _y; // Нижняя граница
public int ObjectMiddleHorizontal => _x + _width / 2; // Середина по горизонтали
public int ObjectMiddleVertical => _y + _height / 2; // Середина по вертикали
public ObjectParameters(int x, int y, int width, int height)
{
_x = x;
_y = y;
_width = width;
_height = height;
}
}
}

17
Tank/Tank/Program.cs Normal file
View File

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

103
Tank/Tank/Properties/Resources.Designer.cs generated Normal file
View File

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

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

91
Tank/Tank/SetGeneric.cs Normal file
View File

@ -0,0 +1,91 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tank
{
internal class SetGeneric<T> where T : class
{
// Массив объектов, которые храним
private readonly T?[] _places;
// Количество объектов в массиве
public int Count => _places.Length;
// Конструктор
public SetGeneric(int count)
{
_places = new T?[count];
}
//Добавление объекта в набор
public int Insert(T tank)
{
int index = -1;
for(int i = 0; i < _places.Length; i++)
{
if (_places[i] == null)
{
index = i; break;
}
}
if (index < 0)
{
return -1;
}
for(int i = index; i > 0; i--)
{
_places[i] = _places[i - 1];
}
_places[0] = tank;
return 0;
}
// Добавление объекта в набор на конкретную позицию
public bool Insert(T tank, int position)
{
if (position < 0 || position >= Count)
return false;
if (_places[position] == null)
{
_places[position] = tank;
return true;
}
int index = -1;
for(int i = position; i < Count; i++)
{
if (_places[i] == null)
{
index = i; break;
}
}
if (index < 0)
return false;
for(int i = index; index > position; i--)
{
_places[i] = _places[i - 1];
}
_places[position] = tank;
return true;
}
// Удаление объекта из набора с конкретной позиции
public bool Remove(int position)
{
if (position < 0 || position >= Count)
return false;
_places[position] = null;
return true;
}
// Получение объекта из набора по позиции
public T? Get(int position)
{
if (position < 0 || position >= Count)
return null;
return _places[position];
}
}
}

15
Tank/Tank/Status.cs Normal file
View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tank
{
public enum Status
{
NotInit = 0,
InProgress = 1,
Finish = 2
}
}

11
Tank/Tank/Tank.csproj Normal file
View File

@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,108 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms.VisualStyles;
using Tank.DrawningObjects;
using Tank.MovementStrategy;
namespace Tank.Generics
{
internal class TanksGenericCollection<T, U>
where T : DrawArmoVehicle
where U : IMoveableObject
{
// Ширина и высота окна прорисовки
private readonly int _pictureWidth;
private readonly int _pictureHeight;
// Размеры занимаемого объектом места
private readonly int _placeSizeWidth = 180;
private readonly int _placeSizeHeight = 90;
// Набор объектов
private readonly SetGeneric<T> _collection;
// Конструктор
public TanksGenericCollection(int pictureWidth, int pictureHeight)
{
int width = pictureWidth / _placeSizeWidth;
int height = pictureHeight / _placeSizeHeight;
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
_collection = new SetGeneric<T>(width * height);
}
// Перегрузка оператора сложения
public static int? operator +(TanksGenericCollection<T, U> collect, T? obj)
{
if (obj == null)
{
return -1;
}
return collect?._collection.Insert(obj);
}
// Перегрузка оператора вычитания
public static bool operator -(TanksGenericCollection<T, U> collect, int pos)
{
T? obj = collect._collection.Get(pos);
if (obj == null)
{
return false;
}
return collect._collection.Remove(pos);
}
// Получение объекта IMoveableObject
public U? GetU(int pos)
{
return (U?)_collection.Get(pos)?.GetMoveableObject;
}
// Вывод всего набора объектов
public Bitmap ShowTanks()
{
Bitmap bmp = new(_pictureWidth, _pictureHeight);
Graphics gr = Graphics.FromImage(bmp);
DrawBackground(gr);
DrawObjects(gr);
return bmp;
}
// Метод отрисовки фона
private void DrawBackground(Graphics g)
{
Pen pen = new(Color.Black, 3);
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);
}
}
// Метод прорисовки объектов
private void DrawObjects(Graphics g)
{
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
for (int i = 0; i < _collection.Count; i++)
{
DrawArmoVehicle? tank = _collection.Get(i);
if (tank == null)
continue;
tank.SetPosition((i % (_pictureWidth / _placeSizeWidth)) * _placeSizeWidth, (i / (_pictureWidth / _placeSizeWidth)) * _placeSizeHeight);
tank.DrawTransport(g);
}
}
}
}