Compare commits

...

34 Commits

Author SHA1 Message Date
nikbel2004@outlook.com
17895a1d63 Готовая Лабораторная работа 8 2023-12-22 21:31:06 +04:00
nikbel2004@outlook.com
7553b06d96 Готовая лабораторная работа 8 2023-12-22 20:40:53 +04:00
nikbel2004@outlook.com
c1eb01d491 Лабораторная работа 8 2023-12-19 12:51:47 +04:00
nikbel2004@outlook.com
07984a1940 Готовая лабораторная работа 7 2023-12-09 03:20:31 +04:00
nikbel2004@outlook.com
065bd53fcf fix 2023-12-09 03:01:21 +04:00
nikbel2004@outlook.com
0630250103 fix 2023-12-09 02:47:52 +04:00
nikbel2004@outlook.com
a3f01ebd0f Доработка 2023-12-09 02:33:19 +04:00
nikbel2004@outlook.com
a853470c18 Лабораторная работа 7 2023-12-09 02:32:08 +04:00
nikbel2004@outlook.com
57ba9fa79f fix 2023-11-29 01:46:26 +04:00
nikbel2004@outlook.com
38eb021ed4 Lab fix 2023-11-29 01:42:58 +04:00
nikbel2004@outlook.com
1d003ace98 LabWork6 2023-11-29 01:08:18 +04:00
nikbel2004@outlook.com
9f84d8ff33 Готовая лабораторная работа 5 2023-11-13 02:37:58 +04:00
nikbel2004@outlook.com
c565f92d0c Готовая лабораторная работа 5 2023-11-13 02:36:16 +04:00
nikbel2004@outlook.com
1ccff34c27 Готовая лабораторная работа 5 2023-11-13 02:35:19 +04:00
nikbel2004@outlook.com
1560754552 Готовая лабораторная работа 5 2023-11-13 02:33:10 +04:00
nikbel2004@outlook.com
7668db2e11 Готовая лабораторная работа 5 2023-11-13 02:28:53 +04:00
nikbel2004@outlook.com
525a6a7d7c Лабораторная работа 5 2023-11-13 02:26:30 +04:00
nikbel2004@outlook.com
02559b8c72 Лабораторная работа 5 2023-11-13 02:24:41 +04:00
nikbel2004@outlook.com
1320e6bc85 Готовая лабораторная 3 2023-10-29 01:23:49 +04:00
nikbel2004@outlook.com
c2af1dfaa4 Готовая лабораторная 3 2023-10-29 01:23:39 +04:00
nikbel2004@outlook.com
afeb74a815 Готовая лабораторная 3 2023-10-29 01:20:02 +04:00
nikbel2004@outlook.com
a974a4341e Правки 2023-10-29 00:39:44 +04:00
nikbel2004@outlook.com
1dd901762a Лабораторная 4 2023-10-28 21:14:08 +04:00
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
41 changed files with 3290 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", "{4C238BAE-E8EA-4DEF-ABB8-DA9CC49797C0}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4C238BAE-E8EA-4DEF-ABB8-DA9CC49797C0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4C238BAE-E8EA-4DEF-ABB8-DA9CC49797C0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4C238BAE-E8EA-4DEF-ABB8-DA9CC49797C0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4C238BAE-E8EA-4DEF-ABB8-DA9CC49797C0}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {73628EAF-BF42-4CF6-87BF-26523028F0DD}
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 System.Drawing;
using Tank.Entities;
using Tank.MovementStrategy;
namespace Tank
{
public class DrawArmoVehicle
{
public EntityArmoVehicle? Tank { get; protected set; }
public int _pictureWidth;
public 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(ArmoVehicle?.AdditionalColor ?? 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,76 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tank.DrawningObjects;
using Tank.Entities;
namespace Tank
{
internal class DrawiningTankEqutables : IEqualityComparer<DrawArmoVehicle?>
{
public bool Equals(DrawArmoVehicle? x, DrawArmoVehicle? y)
{
if (x == null || x.Tank == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.Tank == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.Tank.Speed != y.Tank.Speed)
{
return false;
}
if (x.Tank.Weight != y.Tank.Weight)
{
return false;
}
if (x.Tank.BodyColor != y.Tank.BodyColor)
{
return false;
}
if (x is DrawTank && y is DrawTank)
{
if (x.Tank as EntityTank == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y.Tank as EntityTank == null)
{
throw new ArgumentNullException(nameof(y));
}
if ((x.Tank as EntityTank).AdditionalColor != (y.Tank as EntityTank).AdditionalColor)
{
return false;
}
if ((x.Tank as EntityTank).BodyKit != (y.Tank as EntityTank).BodyKit)
{
return false;
}
if ((x.Tank as EntityTank).Caterpillar != (y.Tank as EntityTank).Caterpillar)
{
return false;
}
if ((x.Tank as EntityTank).Tower != (y.Tank as EntityTank).Tower)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawArmoVehicle obj)
{
return obj.GetHashCode();
}
}
}

View File

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

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

@ -0,0 +1,24 @@
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 void setAdditionalColor(Color color) { AdditionalColor = color; }
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;
}
}
}

View File

@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tank.DrawningObjects;
using Tank.Entities;
namespace Tank
{
public static class ExtentionDrawingTank
{
public static DrawArmoVehicle? CreateDrawTank(this string info, char separatorForObject, int width, int height)
{
string[] strs = info.Split(separatorForObject);
if (strs.Length == 3)
{
return new DrawArmoVehicle(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
}
if (strs.Length == 7)
{
return new DrawTank(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]),
Color.FromName(strs[2]),
Color.FromName(strs[3]),
Convert.ToBoolean(strs[4]),
Convert.ToBoolean(strs[5]),
Convert.ToBoolean(strs[6]), width, height);
}
return null;
}
public static string GetDataForSave(this DrawArmoVehicle vehicle, char separatorForObject)
{
var Vehicle = vehicle.Tank;
if (Vehicle == null)
{
return string.Empty;
}
var str = $"{Vehicle.Speed}{separatorForObject}{Vehicle.Weight}{separatorForObject}{Vehicle.BodyColor.Name}";
if (Vehicle is not EntityTank tank)
{
return str;
}
return $"{str}{separatorForObject}{tank.AdditionalColor.Name}{separatorForObject}{tank.BodyKit}{separatorForObject}{tank.Caterpillar}{separatorForObject}{tank.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>

405
Tank/Tank/FormTankConfig.Designer.cs generated Normal file
View File

@ -0,0 +1,405 @@
namespace Tank
{
partial class FormTankConfig
{
/// <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()
{
ParamsGroup = new GroupBox();
labelTank = new Label();
labelArmoVehicle = new Label();
groupBoxColors = new GroupBox();
panelPink = new Panel();
panelYellow = new Panel();
panelCyan = new Panel();
panelRed = new Panel();
panelBlue = new Panel();
panelOrange = new Panel();
panelGreen = new Panel();
panelSilver = new Panel();
checkBoxCaterpillar = new CheckBox();
checkBoxBodyKit = new CheckBox();
checkBoxTower = new CheckBox();
numericWeight = new NumericUpDown();
numericSpeed = new NumericUpDown();
weightLabel = new Label();
speedLabel = new Label();
panelPictureTank = new Panel();
pictureBox = new PictureBox();
buttonAdd = new Button();
buttonCancel = new Button();
labelColor = new Label();
labelAdditionalColor = new Label();
ParamsGroup.SuspendLayout();
groupBoxColors.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)numericSpeed).BeginInit();
panelPictureTank.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
SuspendLayout();
//
// ParamsGroup
//
ParamsGroup.Controls.Add(labelTank);
ParamsGroup.Controls.Add(labelArmoVehicle);
ParamsGroup.Controls.Add(groupBoxColors);
ParamsGroup.Controls.Add(checkBoxCaterpillar);
ParamsGroup.Controls.Add(checkBoxBodyKit);
ParamsGroup.Controls.Add(checkBoxTower);
ParamsGroup.Controls.Add(numericWeight);
ParamsGroup.Controls.Add(numericSpeed);
ParamsGroup.Controls.Add(weightLabel);
ParamsGroup.Controls.Add(speedLabel);
ParamsGroup.Location = new Point(5, 3);
ParamsGroup.Margin = new Padding(5, 4, 5, 4);
ParamsGroup.Name = "ParamsGroup";
ParamsGroup.Padding = new Padding(5, 4, 5, 4);
ParamsGroup.Size = new Size(240, 740);
ParamsGroup.TabIndex = 0;
ParamsGroup.TabStop = false;
ParamsGroup.Text = "Params Group Box";
//
// labelTank
//
labelTank.BorderStyle = BorderStyle.FixedSingle;
labelTank.Location = new Point(120, 644);
labelTank.Margin = new Padding(5, 0, 5, 0);
labelTank.Name = "labelTank";
labelTank.Size = new Size(87, 55);
labelTank.TabIndex = 10;
labelTank.Text = "Tank";
labelTank.TextAlign = ContentAlignment.MiddleCenter;
labelTank.MouseDown += LabelObject_MouseDown;
//
// labelArmoVehicle
//
labelArmoVehicle.BorderStyle = BorderStyle.FixedSingle;
labelArmoVehicle.Location = new Point(9, 644);
labelArmoVehicle.Margin = new Padding(5, 0, 5, 0);
labelArmoVehicle.Name = "labelArmoVehicle";
labelArmoVehicle.Size = new Size(96, 55);
labelArmoVehicle.TabIndex = 9;
labelArmoVehicle.Text = "ArmoVehicle";
labelArmoVehicle.TextAlign = ContentAlignment.MiddleCenter;
labelArmoVehicle.MouseDown += LabelObject_MouseDown;
//
// groupBoxColors
//
groupBoxColors.Controls.Add(panelPink);
groupBoxColors.Controls.Add(panelYellow);
groupBoxColors.Controls.Add(panelCyan);
groupBoxColors.Controls.Add(panelRed);
groupBoxColors.Controls.Add(panelBlue);
groupBoxColors.Controls.Add(panelOrange);
groupBoxColors.Controls.Add(panelGreen);
groupBoxColors.Controls.Add(panelSilver);
groupBoxColors.Location = new Point(16, 268);
groupBoxColors.Margin = new Padding(5, 4, 5, 4);
groupBoxColors.Name = "groupBoxColors";
groupBoxColors.Padding = new Padding(5, 4, 5, 4);
groupBoxColors.Size = new Size(210, 348);
groupBoxColors.TabIndex = 8;
groupBoxColors.TabStop = false;
groupBoxColors.Text = "Colors";
//
// panelPink
//
panelPink.BackColor = Color.Fuchsia;
panelPink.Location = new Point(107, 276);
panelPink.Margin = new Padding(5, 4, 5, 4);
panelPink.Name = "panelPink";
panelPink.Size = new Size(56, 61);
panelPink.TabIndex = 3;
panelPink.MouseDown += panelColor_MouseDown;
//
// panelYellow
//
panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(107, 108);
panelYellow.Margin = new Padding(5, 4, 5, 4);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(56, 61);
panelYellow.TabIndex = 1;
panelYellow.MouseDown += panelColor_MouseDown;
//
// panelCyan
//
panelCyan.BackColor = Color.Cyan;
panelCyan.Location = new Point(107, 192);
panelCyan.Margin = new Padding(5, 4, 5, 4);
panelCyan.Name = "panelCyan";
panelCyan.Size = new Size(56, 61);
panelCyan.TabIndex = 4;
panelCyan.MouseDown += panelColor_MouseDown;
//
// panelRed
//
panelRed.BackColor = Color.Red;
panelRed.Location = new Point(107, 24);
panelRed.Margin = new Padding(5, 4, 5, 4);
panelRed.Name = "panelRed";
panelRed.Size = new Size(56, 61);
panelRed.TabIndex = 1;
panelRed.MouseDown += panelColor_MouseDown;
//
// panelBlue
//
panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(33, 276);
panelBlue.Margin = new Padding(5, 4, 5, 4);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(56, 61);
panelBlue.TabIndex = 5;
panelBlue.MouseDown += panelColor_MouseDown;
//
// panelOrange
//
panelOrange.BackColor = Color.FromArgb(255, 128, 0);
panelOrange.Location = new Point(33, 108);
panelOrange.Margin = new Padding(5, 4, 5, 4);
panelOrange.Name = "panelOrange";
panelOrange.Size = new Size(56, 61);
panelOrange.TabIndex = 1;
panelOrange.MouseDown += panelColor_MouseDown;
//
// panelGreen
//
panelGreen.BackColor = Color.Lime;
panelGreen.Location = new Point(33, 192);
panelGreen.Margin = new Padding(5, 4, 5, 4);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(56, 61);
panelGreen.TabIndex = 2;
panelGreen.MouseDown += panelColor_MouseDown;
//
// panelSilver
//
panelSilver.BackColor = Color.Silver;
panelSilver.Location = new Point(33, 24);
panelSilver.Margin = new Padding(5, 4, 5, 4);
panelSilver.Name = "panelSilver";
panelSilver.Size = new Size(56, 61);
panelSilver.TabIndex = 0;
panelSilver.MouseDown += panelColor_MouseDown;
//
// checkBoxCaterpillarTank
//
checkBoxCaterpillar.AutoSize = true;
checkBoxCaterpillar.Location = new Point(18, 180);
checkBoxCaterpillar.Margin = new Padding(5, 4, 5, 4);
checkBoxCaterpillar.Name = "checkBoxCaterpillarTank";
checkBoxCaterpillar.Size = new Size(100, 24);
checkBoxCaterpillar.TabIndex = 7;
checkBoxCaterpillar.Text = "Caterpillar";
checkBoxCaterpillar.UseVisualStyleBackColor = true;
//
// checkBoxBodyKit
//
checkBoxBodyKit.AutoSize = true;
checkBoxBodyKit.Location = new Point(18, 149);
checkBoxBodyKit.Margin = new Padding(5, 4, 5, 4);
checkBoxBodyKit.Name = "checkBoxBodyKit";
checkBoxBodyKit.Size = new Size(83, 24);
checkBoxBodyKit.TabIndex = 6;
checkBoxBodyKit.Text = "BodyKit";
checkBoxBodyKit.UseVisualStyleBackColor = true;
//
// checkBoxTower
//
checkBoxTower.AutoSize = true;
checkBoxTower.Location = new Point(18, 216);
checkBoxTower.Margin = new Padding(5, 4, 5, 4);
checkBoxTower.Name = "checkBoxTower";
checkBoxTower.Size = new Size(71, 24);
checkBoxTower.TabIndex = 5;
checkBoxTower.Text = "Tower";
checkBoxTower.UseVisualStyleBackColor = true;
//
// numericWeight
//
numericWeight.Location = new Point(66, 79);
numericWeight.Margin = new Padding(5, 4, 5, 4);
numericWeight.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericWeight.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericWeight.Name = "numericWeight";
numericWeight.Size = new Size(160, 27);
numericWeight.TabIndex = 4;
numericWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// numericSpeed
//
numericSpeed.Location = new Point(66, 36);
numericSpeed.Margin = new Padding(5, 4, 5, 4);
numericSpeed.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericSpeed.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericSpeed.Name = "numericSpeed";
numericSpeed.Size = new Size(160, 27);
numericSpeed.TabIndex = 3;
numericSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// weightLabel
//
weightLabel.AutoSize = true;
weightLabel.Location = new Point(11, 79);
weightLabel.Margin = new Padding(5, 0, 5, 0);
weightLabel.Name = "weightLabel";
weightLabel.Size = new Size(49, 20);
weightLabel.TabIndex = 2;
weightLabel.Text = "weigh";
//
// speedLabel
//
speedLabel.AutoSize = true;
speedLabel.Location = new Point(11, 39);
speedLabel.Margin = new Padding(5, 0, 5, 0);
speedLabel.Name = "speedLabel";
speedLabel.Size = new Size(49, 20);
speedLabel.TabIndex = 1;
speedLabel.Text = "speed";
//
// panel9
//
panelPictureTank.AllowDrop = true;
panelPictureTank.Controls.Add(pictureBox);
panelPictureTank.Location = new Point(266, 116);
panelPictureTank.Margin = new Padding(5, 4, 5, 4);
panelPictureTank.Name = "panel9";
panelPictureTank.Size = new Size(784, 520);
panelPictureTank.TabIndex = 11;
panelPictureTank.DragDrop += PanelObject_DragDrop;
panelPictureTank.DragEnter += PanelObject_DragEnter;
//
// pictureBox
//
pictureBox.Location = new Point(18, 8);
pictureBox.Margin = new Padding(5, 4, 5, 4);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(741, 508);
pictureBox.TabIndex = 0;
pictureBox.TabStop = false;
//
// buttonAdd
//
buttonAdd.Location = new Point(306, 660);
buttonAdd.Margin = new Padding(5, 4, 5, 4);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(200, 62);
buttonAdd.TabIndex = 12;
buttonAdd.Text = "Add";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonOk_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(793, 662);
buttonCancel.Margin = new Padding(5, 4, 5, 4);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(210, 60);
buttonCancel.TabIndex = 13;
buttonCancel.Text = "Cancel";
buttonCancel.UseVisualStyleBackColor = true;
//
// labelColor
//
labelColor.AllowDrop = true;
labelColor.BorderStyle = BorderStyle.FixedSingle;
labelColor.Location = new Point(349, 37);
labelColor.Margin = new Padding(5, 0, 5, 0);
labelColor.Name = "labelColor";
labelColor.Size = new Size(139, 42);
labelColor.TabIndex = 14;
labelColor.Text = "Color";
labelColor.TextAlign = ContentAlignment.MiddleCenter;
labelColor.DragDrop += labelColor_DragDrop;
labelColor.DragEnter += labelColor_DragEnter;
//
// labelAdditionalColor
//
labelAdditionalColor.AllowDrop = true;
labelAdditionalColor.BorderStyle = BorderStyle.FixedSingle;
labelAdditionalColor.Location = new Point(815, 32);
labelAdditionalColor.Margin = new Padding(5, 0, 5, 0);
labelAdditionalColor.Name = "labelAdditionalColor";
labelAdditionalColor.Size = new Size(136, 39);
labelAdditionalColor.TabIndex = 15;
labelAdditionalColor.Text = "Additional color";
labelAdditionalColor.TextAlign = ContentAlignment.MiddleCenter;
labelAdditionalColor.DragDrop += labelColor_DragDrop;
labelAdditionalColor.DragEnter += labelColor_DragEnter;
//
// FormTankConfig
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1066, 744);
Controls.Add(labelAdditionalColor);
Controls.Add(labelColor);
Controls.Add(buttonCancel);
Controls.Add(buttonAdd);
Controls.Add(panelPictureTank);
Controls.Add(ParamsGroup);
Margin = new Padding(5, 4, 5, 4);
Name = "FormTankConfig";
Text = "FormTankConfig";
ParamsGroup.ResumeLayout(false);
ParamsGroup.PerformLayout();
groupBoxColors.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)numericWeight).EndInit();
((System.ComponentModel.ISupportInitialize)numericSpeed).EndInit();
panelPictureTank.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
ResumeLayout(false);
}
#endregion
private GroupBox ParamsGroup;
private CheckBox checkBoxCaterpillar;
private CheckBox checkBoxBodyKit;
private CheckBox checkBoxTower;
private NumericUpDown numericWeight;
private NumericUpDown numericSpeed;
private Label weightLabel;
private Label speedLabel;
private GroupBox groupBoxColors;
private Panel panelPink;
private Panel panelYellow;
private Panel panelCyan;
private Panel panelRed;
private Panel panelBlue;
private Panel panelOrange;
private Panel panelGreen;
private Panel panelSilver;
private Label labelTank;
private Label labelArmoVehicle;
private Panel panelPictureTank;
private PictureBox pictureBox;
private Button buttonAdd;
private Button buttonCancel;
private Label labelColor;
private Label labelAdditionalColor;
}
}

148
Tank/Tank/FormTankConfig.cs Normal file
View File

@ -0,0 +1,148 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tank.DrawningObjects;
using Tank.Entities;
namespace Tank
{
public partial class FormTankConfig : Form
{
Color defaultColor;
// Переменная-выбранный танк
DrawArmoVehicle _tank = null;
// Событие
private event Action<DrawArmoVehicle> EventAddTank;
// Конструктор
public FormTankConfig()
{
InitializeComponent();
panelSilver.MouseDown += panelColor_MouseDown;
panelRed.MouseDown += panelColor_MouseDown;
panelOrange.MouseDown += panelColor_MouseDown;
panelYellow.MouseDown += panelColor_MouseDown;
panelGreen.MouseDown += panelColor_MouseDown;
panelCyan.MouseDown += panelColor_MouseDown;
panelBlue.MouseDown += panelColor_MouseDown;
panelPink.MouseDown += panelColor_MouseDown;
defaultColor = labelColor.BackColor;
buttonCancel.Click += (s, e) => Close();
}
// Отрисовать танк
private void DrawingTank()
{
Bitmap bmp = new Bitmap(pictureBox.Width, pictureBox.Height);
Graphics gr = Graphics.FromImage(bmp);
_tank?.SetPosition(5, 5);
if (_tank is DrawTank)
(_tank as DrawTank).DrawTransport(gr);
else
_tank?.DrawTransport(gr);
pictureBox.Image = bmp;
}
// Добавление события
internal void AddEvent(Action<DrawArmoVehicle> ev)
{
if (EventAddTank == null)
{
EventAddTank = ev;
}
else
{
EventAddTank += ev;
}
}
// Передаем информацию при нажатии на Label
private void LabelObject_MouseDown(object sender, MouseEventArgs e)
{
(sender as Label)?.DoDragDrop((sender as Label)?.Name, DragDropEffects.Move | DragDropEffects.Copy);
}
// Проверка получаемой информации (ее типа на соответствие требуемому)
private void PanelObject_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(DataFormats.Text) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
// Действия при приеме перетаскиваемой информации
private void PanelObject_DragDrop(object sender, DragEventArgs e)
{
switch (e.Data?.GetData(DataFormats.Text).ToString())
{
case "labelArmoVehicle":
_tank = new DrawArmoVehicle((int)numericSpeed.Value, (int)numericWeight.Value, Color.White, pictureBox.Width, pictureBox.Height);
break;
case "labelTank":
_tank = new DrawTank((int)numericSpeed.Value, (int)numericWeight.Value, Color.White, Color.Black, checkBoxBodyKit.Checked, checkBoxCaterpillar.Checked, checkBoxTower.Checked, pictureBox.Width, pictureBox.Height);
break;
}
labelColor.BackColor = defaultColor;
labelAdditionalColor.BackColor = defaultColor;
DrawingTank();
}
// Добавление танка
private void ButtonOk_Click(object sender, EventArgs e)
{
EventAddTank?.Invoke(_tank);
Close();
}
private void panelColor_MouseDown(object sender, MouseEventArgs e)
{
(sender as Panel)?.DoDragDrop((sender as Panel)?.BackColor, DragDropEffects.Move | DragDropEffects.Copy);
}
private void labelColor_DragEnter(object sender, DragEventArgs e)
{
if (e.Data?.GetDataPresent(typeof(Color)) ?? false)
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void labelColor_DragDrop(object sender, DragEventArgs e)
{
if (_tank == null)
return;
((Label)sender).BackColor = (Color)e.Data.GetData(typeof(Color));
switch (((Label)sender).Name)
{
case "labelColor":
_tank.Tank.setBodyColor((Color)e.Data.GetData(typeof(Color)));
break;
case "labelAdditionalColor":
if (!(_tank is DrawTank))
return;
(_tank.Tank as EntityTank).setAdditionalColor((Color)e.Data.GetData(typeof(Color)));
break;
}
DrawingTank();
}
}
}

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>

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

@ -0,0 +1,299 @@
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();
SortColorButton = new Button();
SortTypeButton = new Button();
menuStrip1 = new MenuStrip();
StripMenu = new ToolStripMenuItem();
SaveItem = new ToolStripMenuItem();
LoadItem = new ToolStripMenuItem();
panel2 = new Panel();
DeleteCollectButton = new Button();
CollectionListBox = new ListBox();
AddCollectButton = new Button();
SetTextBox = new TextBox();
label2 = new Label();
UpdateButton = new Button();
DeleteButton = new Button();
AddButton = new Button();
InputNum = new TextBox();
label1 = new Label();
DrawTank = new PictureBox();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
panel1.SuspendLayout();
menuStrip1.SuspendLayout();
panel2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)DrawTank).BeginInit();
SuspendLayout();
//
// panel1
//
panel1.Controls.Add(SortColorButton);
panel1.Controls.Add(SortTypeButton);
panel1.Controls.Add(menuStrip1);
panel1.Controls.Add(panel2);
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(560, 0);
panel1.Margin = new Padding(3, 2, 3, 2);
panel1.Name = "panel1";
panel1.Size = new Size(207, 402);
panel1.TabIndex = 0;
//
// SortColorButton
//
SortColorButton.Location = new Point(27, 56);
SortColorButton.Name = "SortColorButton";
SortColorButton.Size = new Size(163, 23);
SortColorButton.TabIndex = 10;
SortColorButton.Text = "Сортировка по цвету";
SortColorButton.UseVisualStyleBackColor = true;
SortColorButton.Click += ButtonSortByColor_Click;
//
// SortTypeButton
//
SortTypeButton.Location = new Point(27, 30);
SortTypeButton.Name = "SortTypeButton";
SortTypeButton.Size = new Size(163, 23);
SortTypeButton.TabIndex = 9;
SortTypeButton.Text = "Сортировка по типу";
SortTypeButton.UseVisualStyleBackColor = true;
SortTypeButton.Click += ButtonSortByType_Click;
//
// menuStrip1
//
menuStrip1.ImageScalingSize = new Size(20, 20);
menuStrip1.Items.AddRange(new ToolStripItem[] { StripMenu });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Padding = new Padding(5, 2, 0, 2);
menuStrip1.Size = new Size(207, 24);
menuStrip1.TabIndex = 7;
menuStrip1.Text = "menuStrip1";
//
// StripMenu
//
StripMenu.DropDownItems.AddRange(new ToolStripItem[] { SaveItem, LoadItem });
StripMenu.Name = "StripMenu";
StripMenu.Size = new Size(48, 20);
StripMenu.Text = "Файл";
//
// SaveItem
//
SaveItem.Name = "SaveItem";
SaveItem.Size = new Size(133, 22);
SaveItem.Text = "Сохранить";
SaveItem.Click += SaveToolStripMenuItem_Click;
//
// LoadItem
//
LoadItem.Name = "LoadItem";
LoadItem.Size = new Size(133, 22);
LoadItem.Text = "Загрузить";
LoadItem.Click += LoadToolStripMenuItem_Click;
//
// panel2
//
panel2.Controls.Add(DeleteCollectButton);
panel2.Controls.Add(CollectionListBox);
panel2.Controls.Add(AddCollectButton);
panel2.Controls.Add(SetTextBox);
panel2.Controls.Add(label2);
panel2.Location = new Point(14, 105);
panel2.Margin = new Padding(3, 2, 3, 2);
panel2.Name = "panel2";
panel2.Size = new Size(187, 165);
panel2.TabIndex = 6;
//
// DeleteCollectButton
//
DeleteCollectButton.Location = new Point(3, 136);
DeleteCollectButton.Margin = new Padding(3, 2, 3, 2);
DeleteCollectButton.Name = "DeleteCollectButton";
DeleteCollectButton.Size = new Size(182, 22);
DeleteCollectButton.TabIndex = 4;
DeleteCollectButton.Text = "Удалить набор";
DeleteCollectButton.UseVisualStyleBackColor = true;
DeleteCollectButton.Click += ButtonDelObject_Click;
//
// CollectionListBox
//
CollectionListBox.FormattingEnabled = true;
CollectionListBox.ItemHeight = 15;
CollectionListBox.Location = new Point(3, 68);
CollectionListBox.Margin = new Padding(3, 2, 3, 2);
CollectionListBox.Name = "CollectionListBox";
CollectionListBox.Size = new Size(182, 64);
CollectionListBox.TabIndex = 3;
CollectionListBox.SelectedIndexChanged += ListBoxObjects_SelectedIndexChanged;
//
// AddCollectButton
//
AddCollectButton.Location = new Point(3, 42);
AddCollectButton.Margin = new Padding(3, 2, 3, 2);
AddCollectButton.Name = "AddCollectButton";
AddCollectButton.Size = new Size(182, 22);
AddCollectButton.TabIndex = 2;
AddCollectButton.Text = "Добавить набор";
AddCollectButton.UseVisualStyleBackColor = true;
AddCollectButton.Click += ButtonAddObject_Click;
//
// SetTextBox
//
SetTextBox.Location = new Point(2, 17);
SetTextBox.Margin = new Padding(3, 2, 3, 2);
SetTextBox.Name = "SetTextBox";
SetTextBox.Size = new Size(183, 23);
SetTextBox.TabIndex = 1;
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(3, 0);
label2.Name = "label2";
label2.Size = new Size(52, 15);
label2.TabIndex = 0;
label2.Text = "Наборы";
//
// UpdateButton
//
UpdateButton.Location = new Point(9, 369);
UpdateButton.Margin = new Padding(3, 2, 3, 2);
UpdateButton.Name = "UpdateButton";
UpdateButton.Size = new Size(192, 28);
UpdateButton.TabIndex = 4;
UpdateButton.Text = "Обновить коллекцию";
UpdateButton.UseVisualStyleBackColor = true;
UpdateButton.Click += ButtonRefreshCollection_Click;
//
// DeleteButton
//
DeleteButton.Location = new Point(9, 339);
DeleteButton.Margin = new Padding(3, 2, 3, 2);
DeleteButton.Name = "DeleteButton";
DeleteButton.Size = new Size(192, 28);
DeleteButton.TabIndex = 3;
DeleteButton.Text = "Удалить технику";
DeleteButton.UseVisualStyleBackColor = true;
DeleteButton.Click += ButtonRemoveTank_Click;
//
// AddButton
//
AddButton.Location = new Point(9, 281);
AddButton.Margin = new Padding(3, 2, 3, 2);
AddButton.Name = "AddButton";
AddButton.Size = new Size(192, 28);
AddButton.TabIndex = 2;
AddButton.Text = "Добавить технику";
AddButton.UseVisualStyleBackColor = true;
AddButton.Click += ButtonAddTank_Click;
//
// InputNum
//
InputNum.Location = new Point(9, 312);
InputNum.Margin = new Padding(3, 2, 3, 2);
InputNum.Name = "InputNum";
InputNum.Size = new Size(192, 23);
InputNum.TabIndex = 1;
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(107, 88);
label1.Name = "label1";
label1.Size = new Size(83, 15);
label1.TabIndex = 0;
label1.Text = "Инструменты";
//
// DrawTank
//
DrawTank.Dock = DockStyle.Fill;
DrawTank.Location = new Point(0, 0);
DrawTank.Margin = new Padding(3, 2, 3, 2);
DrawTank.Name = "DrawTank";
DrawTank.Size = new Size(560, 402);
DrawTank.TabIndex = 1;
DrawTank.TabStop = false;
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog1";
//
// FormTanksCollections
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(767, 402);
Controls.Add(DrawTank);
Controls.Add(panel1);
Margin = new Padding(3, 2, 3, 2);
Name = "FormTanksCollections";
Text = "CollectionsFrame";
panel1.ResumeLayout(false);
panel1.PerformLayout();
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
panel2.ResumeLayout(false);
panel2.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;
private Panel panel2;
private Button DeleteCollectButton;
private ListBox CollectionListBox;
private Button AddCollectButton;
private TextBox SetTextBox;
private Label label2;
private MenuStrip menuStrip1;
private ToolStripMenuItem StripMenu;
private ToolStripMenuItem SaveItem;
private ToolStripMenuItem LoadItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Button SortColorButton;
private Button SortTypeButton;
}
}

View File

@ -0,0 +1,249 @@
using Microsoft.Extensions.Logging;
using Tank.Exceptions;
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 TanksGenericStorage _storage;
// Логгер
private readonly ILogger _logger;
// Конструктор
public FormTanksCollections(ILogger<FormTanksCollections> logger)
{
InitializeComponent();
_storage = new TanksGenericStorage(DrawTank.Width, DrawTank.Height);
_logger = logger;
}
private void ReloadObjects()
{
int index = CollectionListBox.SelectedIndex;
CollectionListBox.Items.Clear();
foreach (var key in _storage.Keys)
{
CollectionListBox.Items.Add(key.Name);
}
if (CollectionListBox.Items.Count > 0 && (index == -1 || index
>= CollectionListBox.Items.Count))
{
CollectionListBox.SelectedIndex = 0;
}
else if (CollectionListBox.Items.Count > 0 && index > -1 &&
index < CollectionListBox.Items.Count)
{
CollectionListBox.SelectedIndex = index;
}
}
private void ButtonAddObject_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(SetTextBox.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Коллекция не добавлена, не все данные заполнены");
return;
}
_storage.AddSet(SetTextBox.Text);
ReloadObjects();
_logger.LogInformation($"Добавлен набор: {SetTextBox.Text}");
}
private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e)
{
DrawTank.Image = _storage[CollectionListBox.SelectedItem?.ToString() ?? string.Empty]?.ShowTanks();
}
private void ButtonDelObject_Click(object sender, EventArgs e)
{
if (CollectionListBox.SelectedIndex == -1)
{
_logger.LogWarning("Удаление невыбранного набора");
return;
}
string nameSet = CollectionListBox.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Удалить объект {nameSet}?", "Удаление", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(nameSet);
ReloadObjects();
_logger.LogInformation($"Набор '{nameSet}' удален");
}
_logger.LogWarning("Отмена удаления набора");
}
private void AddTank(DrawArmoVehicle tank)
{
if (CollectionListBox.SelectedIndex == -1)
{
return;
}
var obj = _storage[CollectionListBox.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
_logger.LogWarning("Добавление пустого объекта");
return;
}
try
{
if ((obj + tank) != false)
{
MessageBox.Show("Объект добавлен");
DrawTank.Image = obj.ShowTanks();
_logger.LogInformation($"Добавлен объект {obj}");
}
}
catch (TankStorageOverflowException ex)
{
MessageBox.Show(ex.Message);
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning($"{ex.Message} в наборе {CollectionListBox.SelectedItem.ToString()}");
}
catch (ApplicationException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"добавление танка неуспешно {ex.Message}");
}
}
private void ButtonAddTank_Click(object sender, EventArgs e)
{
// Проверка на вызов формочки
if (CollectionListBox.SelectedIndex == -1)
{
return;
}
var obj = _storage[CollectionListBox.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
FormTankConfig form = new FormTankConfig();
form.Show();
form.AddEvent(AddTank);
}
private void ButtonRemoveTank_Click(object sender, EventArgs e)
{
if (CollectionListBox.SelectedIndex == -1)
{
_logger.LogWarning("Удаление объекта из несуществующего набора");
return;
}
var obj = _storage[CollectionListBox.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
_logger.LogWarning("Отмена удаления объекта");
return;
}
int pos = Convert.ToInt32(InputNum.Text);
try
{
if (obj - pos != null)
{
MessageBox.Show("Объект удален");
_logger.LogInformation($"Удален объект с позиции{pos}");
DrawTank.Image = obj.ShowTanks();
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning($"Не удалось удалить объект из набора {CollectionListBox.SelectedItem.ToString()}");
}
}
catch (TankNotFoundException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"{ex.Message} из набора {CollectionListBox.SelectedItem.ToString()}");
}
}
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
{
if (CollectionListBox.SelectedIndex == -1)
{
return;
}
var obj = _storage[CollectionListBox.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
DrawTank.Image = obj.ShowTanks();
}
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Данные загружены в файл {saveFileDialog.FileName}");
}
catch (Exception ex)
{
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogWarning($"Не удалось сохранить информацию в файл: {ex.Message}");
}
}
}
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.LoadData(openFileDialog.FileName);
ReloadObjects();
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Данные загружены из файла {openFileDialog.FileName}");
}
catch (Exception ex)
{
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogWarning($"Не удалось загрузить информацию из файла: {ex.Message}");
}
}
}
private void ButtonSortByType_Click(object sender, EventArgs e) => CompareTank(new TankCompareByType());
private void ButtonSortByColor_Click(object sender, EventArgs e) => CompareTank(new TankCompareByColor());
private void CompareTank(IComparer<DrawArmoVehicle?> comparer)
{
if (CollectionListBox.SelectedIndex == -1)
return;
var obj = _storage[CollectionListBox.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
return;
obj.Sort(comparer);
DrawTank.Image = obj.ShowTanks();
}
}
}

View File

@ -0,0 +1,129 @@
<?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>
<metadata name="menuStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>344, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>187, 17</value>
</metadata>
</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;
}
}
}

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

@ -0,0 +1,44 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Tank;
namespace Tank
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
ApplicationConfiguration.Initialize();
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormTanksCollections>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormTanksCollections>().AddLogging(option =>
{
string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile(path: $"{pathNeed}appSetting.json", optional: false, reloadOnChange: true).Build();
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

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

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

@ -0,0 +1,92 @@
using Tank.Exceptions;
using Microsoft.VisualBasic;
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 List<T?> _places;
public int Count => _places.Count;
// Максимальное количество объектов
private readonly int _maxCount;
// Сортировка набора объектов
public void SortSet(IComparer<T?> comparer) => _places.Sort(comparer);
// Конструктор
public SetGeneric(int count)
{
_maxCount = count;
_places = new List<T?>(_maxCount);
}
// Добавление объекта в набор
public bool Insert(T tank, IEqualityComparer<T?>? equal = null)
{
return Insert(tank, 0, equal);
}
// Добавление на конкретную позицию
public bool Insert(T tank, int position, IEqualityComparer<T?>? equal = null)
{
if (position < 0 || position >= _maxCount)
throw new TankNotFoundException(position); // По позиции
if (Count >= _maxCount)
throw new TankStorageOverflowException(_maxCount); // Макс количество в коллекции
if (equal != null && _places.Contains<T>(tank, equal))
throw new ApplicationException("уже существует");
_places.Insert(0, tank);
return true;
}
// Удаление объекта из набора с конкретной позиции
public bool Remove(int position)
{
if (position < 0 || position > _maxCount || position >= Count)
throw new TankNotFoundException(position);
_places.RemoveAt(position);
return true;
}
// Получение объекта из набора по позиции
public T? this[int position]
{
get
{
if (position < 0 || position >= Count)
return null;
return _places[position];
}
set
{
if (position < 0 || position > _maxCount || Count == _maxCount)
return;
_places[position] = value;
}
}
// Проход по списку
public IEnumerable<T?> GetTanks(int? maxTanks = null)
{
for (int i = 0; i < _places.Count; ++i)
{
yield return _places[i];
if (maxTanks.HasValue && i == maxTanks.Value)
{
yield break;
}
}
}
}
}

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
}
}

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

@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.0" />
<PackageReference Include="Serilog.Extensions.Hosting" Version="8.0.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tank.DrawningObjects;
using Tank.Entities;
namespace Tank
{
internal class TankCompareByColor : IComparer<DrawArmoVehicle?>
{
public int Compare(DrawArmoVehicle? x, DrawArmoVehicle? y)
{
if (x == null || x.Tank == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.Tank == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.Tank.BodyColor != y.Tank.BodyColor)
{
return x.Tank.BodyColor.Name.CompareTo(y.Tank.BodyColor.Name);
}
if (x.GetType() == y.GetType() && x is DrawTank)
{
return (x.Tank as EntityTank).AdditionalColor.Name.CompareTo((y.Tank as EntityTank).AdditionalColor.Name);
}
var speedCompare = x.Tank.Speed.CompareTo(y.Tank.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.Tank.Weight.CompareTo(y.Tank.Weight);
}
}
}

View File

@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tank.DrawningObjects;
namespace Tank
{
internal class TankCompareByType : IComparer<DrawArmoVehicle?>
{
public int Compare(DrawArmoVehicle? x, DrawArmoVehicle? y)
{
if (x == null || x.Tank == null)
{
throw new ArgumentNullException(nameof(x));
}
if (y == null || y.Tank == null)
{
throw new ArgumentNullException(nameof(y));
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.Tank.Speed.CompareTo(y.Tank.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.Tank.Weight.CompareTo(y.Tank.Weight);
}
}
}

View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace Tank.Exceptions
{
[Serializable]
internal class TankNotFoundException : ApplicationException
{
public TankNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
public TankNotFoundException() : base() { }
public TankNotFoundException(string message) : base(message) { }
public TankNotFoundException(string message, Exception exception) : base(message, exception) { }
protected TankNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace Tank
{
[Serializable]
internal class TankStorageOverflowException : ApplicationException
{
public TankStorageOverflowException(int count) : base($"В наборе превышено допустимое количество: {count}") { }
public TankStorageOverflowException() : base() { }
public TankStorageOverflowException(string message) : base(message) { }
public TankStorageOverflowException(string message, Exception exception) : base(message, exception) { }
protected TankStorageOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tank
{
internal class TankCollectionInfo : IEquatable<TankCollectionInfo>
{
public string Name { get; private set; }
public string Description { get; private set; }
public TankCollectionInfo(string name, string description)
{
Name = name;
Description = description;
}
public bool Equals(TankCollectionInfo? other)
{
if (other == null || Name == null || other.Name == null) return false;
if (Name == other?.Name) return true;
throw new NotImplementedException();
}
public override int GetHashCode()
{
return Name?.GetHashCode() ?? 0;
}
}
}

View File

@ -0,0 +1,113 @@
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 IEnumerable<T?> GetTanks => _collection.GetTanks();
// Конструктор
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 bool operator +(TanksGenericCollection<T, U> collect, T? obj)
{
if (obj == null)
{
return false;
}
return (bool)collect?._collection.Insert(obj, new DrawiningTankEqutables());
}
// Перегрузка оператора вычитания
public static T? operator -(TanksGenericCollection<T, U> collect, int pos)
{
T? obj = collect._collection[pos];
collect._collection.Remove(pos);
return obj;
}
// Сортировка
public void Sort(IComparer<T> comparer) => _collection.SortSet(comparer);
// Получение объекта IMoveableObject
public U? GetU(int pos)
{
return (U?)_collection[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;
int i = 0;
foreach(var tank in _collection.GetTanks())
{
if (tank != null)
{
tank._pictureWidth = _pictureWidth;
tank._pictureHeight = _pictureHeight;
tank.SetPosition((i % (_pictureWidth / _placeSizeWidth)) * _placeSizeWidth, (i / (_pictureWidth / _placeSizeWidth)) * _placeSizeHeight);
tank.DrawTransport(g);
}
i++;
}
}
}
}

View File

@ -0,0 +1,147 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tank.Generics;
using Tank.DrawningObjects;
using Tank.MovementStrategy;
using Tank.Exceptions;
using Tank.Entities;
namespace Tank
{
internal class TanksGenericStorage
{
// Словарь
readonly Dictionary<TankCollectionInfo, TanksGenericCollection<DrawArmoVehicle, DrawingObjectTank>> _tankStorages;
// Возвращение списка названий наборов
public List<TankCollectionInfo> Keys => _tankStorages.Keys.ToList();
private readonly int _pictureWidth;
private readonly int _pictureHeight;
private static readonly char _separatorForKeyValue = '|';
private readonly char _separatorRecords = ';';
private static readonly char _separatorForObject = ':';
// Конструктор
public TanksGenericStorage(int pictureWidth, int pictureHeight)
{
_tankStorages = new Dictionary<TankCollectionInfo, TanksGenericCollection<DrawArmoVehicle, DrawingObjectTank>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
// Добавление набора
public void AddSet(string name)
{
TankCollectionInfo Info = new TankCollectionInfo(name, string.Empty);
if (_tankStorages.ContainsKey(Info)) return;
_tankStorages[Info] = new TanksGenericCollection<DrawArmoVehicle, DrawingObjectTank>(_pictureWidth, _pictureHeight);
}
// Удаление набора
public void DelSet(string name)
{
TankCollectionInfo Info = new TankCollectionInfo(name, string.Empty);
if (!_tankStorages.ContainsKey(Info)) return;
_tankStorages.Remove(Info);
}
// Доступ к набору
public TanksGenericCollection<DrawArmoVehicle, DrawingObjectTank>?
this[string ind]
{
get
{
TankCollectionInfo Info = new TankCollectionInfo(ind, string.Empty);
if (_tankStorages.ContainsKey(Info)) return _tankStorages[Info];
return null;
}
}
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<TankCollectionInfo, TanksGenericCollection<DrawArmoVehicle, DrawingObjectTank>> record in _tankStorages)
{
StringBuilder records = new();
foreach (DrawArmoVehicle? elem in record.Value.GetTanks)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key.Name}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
throw new InvalidOperationException("File not found, невалиданя операция, нет данных для сохранения");
}
using (StreamWriter writer = new StreamWriter(filename))
{
writer.WriteLine("TankStorage");
writer.Write(data.ToString());
}
}
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не найден");
}
using (StreamReader reader = new StreamReader(filename))
{
string checker = reader.ReadLine();
if (checker == null)
throw new NullReferenceException("Нет данных для загрузки");
if (!checker.StartsWith("TankStorage"))
{
//если нет такой записи, то это не те данные
throw new FormatException("Неверный формат данных");
}
_tankStorages.Clear();
string strs;
bool firstinit = true;
while ((strs = reader.ReadLine()) != null)
{
if (strs == null && firstinit)
throw new NullReferenceException("Нет данных для загрузки");
if (strs == null)
break;
firstinit = false;
string name = strs.Split('|')[0];
TanksGenericCollection<DrawArmoVehicle, DrawingObjectTank> collection = new(_pictureWidth, _pictureHeight);
foreach (string data in strs.Split('|')[1].Split(';'))
{
DrawArmoVehicle? vehicle = data?.CreateDrawTank(_separatorForObject, _pictureWidth, _pictureHeight);
if (vehicle != null)
{
try
{
_ = collection + vehicle;
}
catch (TankNotFoundException e)
{
throw e;
}
catch (TankStorageOverflowException e)
{
throw e;
}
}
}
_tankStorages.Add(new TankCollectionInfo(name, string.Empty), collection);
}
}
}
}
}

20
Tank/Tank/appSetting.json Normal file
View File

@ -0,0 +1,20 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/log_.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "Tank"
}
}
}