Compare commits

...

8 Commits
main ... Lab7

Author SHA1 Message Date
cae1d549b4 Lab7 WarmlyShip Barsukov 2023-12-02 03:02:16 +04:00
73b9099be3 Lab6 WarmlyShip Barsukov 2023-11-18 03:34:52 +04:00
1066642b8d Lab5 WarmlyShip Barsukov 2023-11-18 02:35:37 +04:00
bfde6534c3 Lab4 WarmlyShip Barsukov 2023-11-18 00:12:24 +04:00
99de878d24 Lab3 WarmlyShip Barsukov 2023-11-17 22:36:23 +04:00
a89f92cdc3 Lab2 WarmlyShip Barsukov 2023-10-07 21:07:37 +04:00
9a12da874a Lab1 WarmlySlip Barsukov final2 2023-10-06 03:20:04 +04:00
055a2f3bda Lab1 WarmlyShip Barsukov final 2023-10-06 03:13:36 +04:00
37 changed files with 2745 additions and 0 deletions

View File

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.5.33627.172
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProjectWarmlyShip", "ProjectWarmlyShip\ProjectWarmlyShip.csproj", "{D1F03A6D-14AA-406C-94BB-CB5E055E7830}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{D1F03A6D-14AA-406C-94BB-CB5E055E7830}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D1F03A6D-14AA-406C-94BB-CB5E055E7830}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D1F03A6D-14AA-406C-94BB-CB5E055E7830}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D1F03A6D-14AA-406C-94BB-CB5E055E7830}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {47092368-4841-45BC-8FA6-9653B7B37C6E}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,71 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectWarmlyShip.DrawingObjects;
namespace ProjectWarmlyShip.MovementStrategy
{
public abstract class AbstractStrategy
{
private IMoveableObject? _movebleObject;
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;
_movebleObject = moveableObject;
FieldWidth = width;
FieldHeight = height;
}
public void MakeStep()
{
if (_state != Status.InProgress)
{
return;
}
if (IsTargetDestination())
{
_state = Status.Finish;
return;
}
MoveToTarget();
}
protected bool MoveLeft() => MoveTo(DirectionType.Left);
protected bool MoveRight() => MoveTo(DirectionType.Right);
protected bool MoveUp() => MoveTo(DirectionType.Up);
protected bool MoveDown() => MoveTo(DirectionType.Down);
protected ObjectParametrs? GetObjectParametrs => _movebleObject?.GetObjectPosition;
protected int? GetStep()
{
if (_state != Status.InProgress)
{
return null;
}
return _movebleObject?.GetStep;
}
protected abstract void MoveToTarget();
protected abstract bool IsTargetDestination();
private bool MoveTo(DirectionType directionType)
{
if (_state != Status.InProgress)
{
return false;
}
if (_movebleObject?.CheckCanMove(directionType) ?? false)
{
_movebleObject.MoveObject(directionType);
return true;
}
return false;
}
}
}

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": "WarmlyShip"
}
}
}

View File

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

View File

@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectWarmlyShip.DrawingObjects;
namespace ProjectWarmlyShip.MovementStrategy
{
public class DrawingObjectShip : IMoveableObject
{
private readonly DrawingShip? _drawingShip = null;
public DrawingObjectShip(DrawingShip drawingShip)
{
_drawingShip = drawingShip;
}
public ObjectParametrs? GetObjectPosition
{
get
{
if (_drawingShip == null || _drawingShip.EntityShip == null)
{
return null;
}
return new ObjectParametrs(_drawingShip.GetPosX,
_drawingShip.GetPosY, _drawingShip.GetWidth,
_drawingShip.GetHeight);
}
}
public int GetStep => (int)(_drawingShip?.EntityShip?.Step ?? 0);
public bool CheckCanMove(DirectionType direction) =>
_drawingShip?.CanMove(direction) ?? false;
public void MoveObject(DirectionType direction) =>
_drawingShip?.MoveTransport(direction);
}
}

View File

@ -0,0 +1,132 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectWarmlyShip.Entities;
using ProjectWarmlyShip.MovementStrategy;
namespace ProjectWarmlyShip.DrawingObjects
{
public class DrawingShip
{
public EntityShip? EntityShip { get; protected set; }
private int _pictureWidth;
private int _pictureHeight;
protected int _startPosX;
protected int _startPosY;
protected readonly int _shipWidth = 100;
protected readonly int _shipHeight = 30;
public IMoveableObject GetMoveableObject => new DrawingObjectShip(this);
public DrawingShip(int speed, double weight, Color mainColor, int width, int heigth)
{
if (width <= _shipWidth || heigth <= _shipHeight)
{
return;
}
_pictureWidth = width;
_pictureHeight = heigth;
EntityShip = new EntityShip(speed, weight, mainColor);
}
protected DrawingShip(int speed, double weight,
Color mainColor, int width, int heigth,
int shipWidth, int shipHeight)
{
if (width <= shipWidth || heigth <= shipHeight)
{
return;
}
_pictureHeight = heigth;
_pictureWidth = width;
_shipHeight = shipHeight;
_shipWidth = shipWidth;
EntityShip = new EntityShip(speed, weight, mainColor);
}
public void SetPosition(int x, int y)
{
if (x < 0 || y < 0 || x + _shipWidth > _pictureWidth || y + _shipHeight > _pictureHeight)
{
x = 10;
y = 10;
}
_startPosX = x;
_startPosY = y;
}
public int GetPosX => _startPosX;
public int GetPosY => _startPosY;
public int GetWidth => _shipWidth;
public int GetHeight => _shipHeight;
public bool CanMove(DirectionType direction)
{
if (EntityShip == null)
{
return false;
}
return direction switch
{
DirectionType.Left => _startPosX - EntityShip.Step > 0,
DirectionType.Up => _startPosY - EntityShip.Step > 0,
DirectionType.Right => _startPosX + EntityShip.Step + _shipWidth <= _pictureWidth,
DirectionType.Down => _startPosY + EntityShip.Step + _shipHeight <= _pictureHeight,
_ => false,
};
}
public void MoveTransport(DirectionType direction)
{
if (!CanMove(direction) || EntityShip == null)
{
return;
}
switch (direction)
{
case DirectionType.Left:
_startPosX -= (int)EntityShip.Step;
break;
case DirectionType.Up:
_startPosY -= (int)EntityShip.Step;
break;
case DirectionType.Right:
_startPosX += (int)EntityShip.Step;
break;
case DirectionType.Down:
_startPosY += (int)EntityShip.Step;
break;
}
}
public virtual void DrawTrasport(Graphics g)
{
if (EntityShip == null)
{
return;
}
Pen pen = new(Color.Black);
Brush mainBrush = new SolidBrush(EntityShip.MainColor);
//палуба
g.FillRectangle(mainBrush, _startPosX + 30, _startPosY, 60, 10);
g.DrawRectangle(pen, _startPosX + 30, _startPosY, 60, 10);
//корпус
g.FillPolygon(mainBrush, new Point[]
{
new Point(_startPosX, _startPosY + 10),
new Point(_startPosX + 100, _startPosY + 10),
new Point(_startPosX + 90, _startPosY + 30),
new Point(_startPosX + 20, _startPosY + 30),
new Point(_startPosX, _startPosY + 10),
}
);
g.DrawPolygon(pen, new Point[]
{
new Point(_startPosX, _startPosY + 10),
new Point(_startPosX + 100, _startPosY + 10),
new Point(_startPosX + 90, _startPosY + 30),
new Point(_startPosX + 20, _startPosY + 30),
new Point(_startPosX, _startPosY + 10),
}
);
//якорь
g.DrawLine(pen, _startPosX + 25, _startPosY + 15, _startPosX + 25, _startPosY + 25);
g.DrawLine(pen, _startPosX + 20, _startPosY + 20, _startPosX + 30, _startPosY + 20);
g.DrawLine(pen, _startPosX + 23, _startPosY + 25, _startPosX + 27, _startPosY + 25);
}
}
}

View File

@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectWarmlyShip.Entities;
namespace ProjectWarmlyShip.DrawingObjects
{
public class DrawingWarmlyShip : DrawingShip
{
public DrawingWarmlyShip(int speed, double weight,
Color mainColor, Color optionalColor, bool pipes,
bool fuelCompartment, int width, int height) :
base(speed, weight, mainColor, width, height, 100, 60)
{
if (EntityShip != null)
{
EntityShip = new EntityWarmlyShip(speed, weight, mainColor,
optionalColor, pipes, fuelCompartment);
}
}
public override void DrawTrasport(Graphics g)
{
if (EntityShip is not EntityWarmlyShip warmlyShip)
{
return;
}
Pen pen = new(Color.Black);
Brush optionalBrush = new SolidBrush(warmlyShip.OptionalColor);
if (warmlyShip.Pipes)
{
g.FillRectangle(optionalBrush, _startPosX + 70, _startPosY, 10, 30);
g.FillRectangle(optionalBrush, _startPosX + 50, _startPosY + 10, 10, 20);
g.DrawRectangle(pen, _startPosX + 50, _startPosY + 10, 10, 20);
g.DrawRectangle(pen, _startPosX + 70, _startPosY, 10, 30);
}
if (warmlyShip.FuelCompartment)
{
g.FillRectangle(optionalBrush, _startPosX + 10, _startPosY + 30, 10, 10);
g.DrawRectangle(pen, _startPosX + 10, _startPosY + 30, 10, 10);
}
_startPosY += 30;
base.DrawTrasport(g);
_startPosY -= 30;
}
}
}

View File

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

View File

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectWarmlyShip.Entities
{
public class EntityWarmlyShip : EntityShip
{
public Color OptionalColor { get; set; }
public bool Pipes { get; private set; }
public bool FuelCompartment { get; private set; }
public EntityWarmlyShip(int speed, double weight,
Color mainColor, Color optionalColor,
bool pipes, bool fuelCompartment) : base(speed, weight, mainColor)
{
OptionalColor = optionalColor;
Pipes = pipes;
FuelCompartment = fuelCompartment;
}
}
}

View File

@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectWarmlyShip.DrawingObjects;
using ProjectWarmlyShip.Entities;
namespace ProjectWarmlyShip
{
public static class ExtentionDrawingShip
{
public static DrawingShip? CreateDrawingShip(this string info,
char separatorForObjects, int width, int height)
{
string[] strs = info.Split(separatorForObjects);
if (strs.Length == 3)
{
return new DrawingShip(Convert.ToInt32(strs[0]), Convert.ToInt32(strs[1]),
Color.FromName(strs[2]), width, height);
}
if (strs.Length == 6)
{
return new DrawingWarmlyShip(Convert.ToInt32(strs[0]), Convert.ToInt32(strs[1]),
Color.FromName(strs[2]), Color.FromName(strs[3]), Convert.ToBoolean(strs[4]),
Convert.ToBoolean(strs[5]), width, height);
}
return null;
}
public static string GetDataForSave(this DrawingShip drawingShip, char separatorForObjects)
{
var ship = drawingShip.EntityShip;
if (ship == null)
{
return string.Empty;
}
var str =
$"{ship.Speed}{separatorForObjects}{ship.Weight}{separatorForObjects}{ship.MainColor.Name}";
if (ship is not EntityWarmlyShip warmlyShip)
{
return str;
}
return
$"{str}{separatorForObjects}{warmlyShip.OptionalColor.Name}{separatorForObjects}" +
$"{warmlyShip.Pipes}{separatorForObjects}{warmlyShip.FuelCompartment}";
}
}
}

View File

@ -0,0 +1,244 @@
namespace ProjectWarmlyShip
{
partial class FormShipCollection
{
/// <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()
{
pictureBoxCollection = new PictureBox();
Tools = new GroupBox();
Sets = new GroupBox();
listBoxStorage = new ListBox();
DeleteSetButton = new Button();
AddSetButton = new Button();
textBoxStorageName = new TextBox();
maskedTextBoxNumber = new TextBox();
buttonRefresh = new Button();
buttonDeleteShip = new Button();
buttonAddShip = new Button();
StripMenu = new MenuStrip();
fileToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
SaveFileDialog = new SaveFileDialog();
OpenFileDialog = new OpenFileDialog();
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit();
Tools.SuspendLayout();
Sets.SuspendLayout();
StripMenu.SuspendLayout();
SuspendLayout();
//
// pictureBoxCollection
//
pictureBoxCollection.Location = new Point(0, 25);
pictureBoxCollection.Name = "pictureBoxCollection";
pictureBoxCollection.Size = new Size(700, 460);
pictureBoxCollection.TabIndex = 0;
pictureBoxCollection.TabStop = false;
//
// Tools
//
Tools.Controls.Add(Sets);
Tools.Controls.Add(maskedTextBoxNumber);
Tools.Controls.Add(buttonRefresh);
Tools.Controls.Add(buttonDeleteShip);
Tools.Controls.Add(buttonAddShip);
Tools.Location = new Point(700, 25);
Tools.Name = "Tools";
Tools.Size = new Size(180, 460);
Tools.TabIndex = 1;
Tools.TabStop = false;
Tools.Text = "Tools";
//
// Sets
//
Sets.Controls.Add(listBoxStorage);
Sets.Controls.Add(DeleteSetButton);
Sets.Controls.Add(AddSetButton);
Sets.Controls.Add(textBoxStorageName);
Sets.Location = new Point(10, 20);
Sets.Name = "Sets";
Sets.Size = new Size(165, 235);
Sets.TabIndex = 5;
Sets.TabStop = false;
Sets.Text = "Sets";
//
// listBoxStorage
//
listBoxStorage.FormattingEnabled = true;
listBoxStorage.ItemHeight = 15;
listBoxStorage.Location = new Point(5, 85);
listBoxStorage.Name = "listBoxStorage";
listBoxStorage.Size = new Size(154, 109);
listBoxStorage.TabIndex = 7;
listBoxStorage.SelectedIndexChanged += ListBoxObjects_SelectedIndexChanged;
//
// DeleteSetButton
//
DeleteSetButton.Location = new Point(5, 200);
DeleteSetButton.Name = "DeleteSetButton";
DeleteSetButton.Size = new Size(155, 30);
DeleteSetButton.TabIndex = 6;
DeleteSetButton.Text = "Delete Set";
DeleteSetButton.UseVisualStyleBackColor = true;
DeleteSetButton.Click += ButtonDeleteObjectClick;
//
// AddSetButton
//
AddSetButton.Location = new Point(6, 51);
AddSetButton.Name = "AddSetButton";
AddSetButton.Size = new Size(155, 30);
AddSetButton.TabIndex = 5;
AddSetButton.Text = "Add Set";
AddSetButton.UseVisualStyleBackColor = true;
AddSetButton.Click += ButtonAddObject_Click;
//
// textBoxStorageName
//
textBoxStorageName.Location = new Point(5, 20);
textBoxStorageName.Name = "textBoxStorageName";
textBoxStorageName.Size = new Size(155, 23);
textBoxStorageName.TabIndex = 5;
//
// maskedTextBoxNumber
//
maskedTextBoxNumber.Location = new Point(10, 320);
maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(165, 23);
maskedTextBoxNumber.TabIndex = 4;
//
// buttonRefresh
//
buttonRefresh.Location = new Point(10, 405);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(165, 50);
buttonRefresh.TabIndex = 2;
buttonRefresh.Text = "Refresh";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += ButtonRefreshCollection;
//
// buttonDeleteShip
//
buttonDeleteShip.Location = new Point(10, 350);
buttonDeleteShip.Name = "buttonDeleteShip";
buttonDeleteShip.Size = new Size(165, 50);
buttonDeleteShip.TabIndex = 1;
buttonDeleteShip.Text = "Delete Ship";
buttonDeleteShip.UseVisualStyleBackColor = true;
buttonDeleteShip.Click += ButtonRemoveShip_Click;
//
// buttonAddShip
//
buttonAddShip.Location = new Point(10, 260);
buttonAddShip.Name = "buttonAddShip";
buttonAddShip.Size = new Size(165, 50);
buttonAddShip.TabIndex = 0;
buttonAddShip.Text = "Add Ship";
buttonAddShip.UseVisualStyleBackColor = true;
buttonAddShip.Click += ButtonAddShip_Click;
//
// StripMenu
//
StripMenu.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem });
StripMenu.Location = new Point(0, 0);
StripMenu.Name = "StripMenu";
StripMenu.Size = new Size(884, 24);
StripMenu.TabIndex = 2;
StripMenu.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
fileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
fileToolStripMenuItem.Name = "fileToolStripMenuItem";
fileToolStripMenuItem.Size = new Size(37, 20);
fileToolStripMenuItem.Text = "File";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.Size = new Size(180, 22);
saveToolStripMenuItem.Text = "Save";
saveToolStripMenuItem.Click += SaveToolStripMenu_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.Size = new Size(180, 22);
loadToolStripMenuItem.Text = "Load";
loadToolStripMenuItem.Click += LoadToolStripMenu_Click;
//
// SaveFileDialog
//
SaveFileDialog.Filter = "txt file | *.txt";
//
// OpenFileDialog
//
OpenFileDialog.FileName = "openFileDialog1";
OpenFileDialog.Filter = "txt file | *.txt";
//
// FormShipCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(884, 491);
Controls.Add(Tools);
Controls.Add(pictureBoxCollection);
Controls.Add(StripMenu);
MainMenuStrip = StripMenu;
Name = "FormShipCollection";
Text = "FormShipCollection";
((System.ComponentModel.ISupportInitialize)pictureBoxCollection).EndInit();
Tools.ResumeLayout(false);
Tools.PerformLayout();
Sets.ResumeLayout(false);
Sets.PerformLayout();
StripMenu.ResumeLayout(false);
StripMenu.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
private PictureBox pictureBoxCollection;
private GroupBox Tools;
private TextBox maskedTextBoxNumber;
private Button buttonRefresh;
private Button buttonDeleteShip;
private Button buttonAddShip;
private GroupBox Sets;
private ListBox listBoxStorage;
private Button DeleteSetButton;
private Button AddSetButton;
private TextBox textBoxStorageName;
private MenuStrip StripMenu;
private ToolStripMenuItem fileToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog SaveFileDialog;
private OpenFileDialog OpenFileDialog;
}
}

View File

@ -0,0 +1,220 @@
using ProjectWarmlyShip.DrawingObjects;
using ProjectWarmlyShip.Generics;
using ProjectWarmlyShip.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;
using ProjectWarmlyShip.DrawingObjects;
using ProjectWarmlyShip.Generics;
using ProjectWarmlyShip.MovementStrategy;
using ProjectWarmlyShip.Exceptions;
using Microsoft.Extensions.Logging;
namespace ProjectWarmlyShip
{
public partial class FormShipCollection : Form
{
public int GetWidth()
{
return pictureBoxCollection.Width;
}
public int GetHeight()
{
return pictureBoxCollection.Height;
}
private readonly ShipsGenericStorage _storage;
private readonly ILogger _logger;
public FormShipCollection(ILogger<FormShipCollection> logger)
{
InitializeComponent();
_storage = new ShipsGenericStorage(pictureBoxCollection.Width,
pictureBoxCollection.Height);
_logger = logger;
}
private void ReloadObjects()
{
int index = listBoxStorage.SelectedIndex;
listBoxStorage.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++)
{
listBoxStorage.Items.Add(_storage.Keys[i]);
}
if (listBoxStorage.Items.Count > 0 && (index == -1 || index >= listBoxStorage.Items.Count))
{
listBoxStorage.SelectedIndex = 0;
}
else if (listBoxStorage.Items.Count > 0 && index > -1 && index < listBoxStorage.Items.Count)
{
listBoxStorage.SelectedIndex = index;
}
}
private void ButtonAddObject_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxStorageName.Text))
{
MessageBox.Show("Input not complete", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
_logger.LogInformation($"Added set: {textBoxStorageName.Text}");
}
private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBoxCollection.Image =
_storage[listBoxStorage.SelectedItem?.ToString() ?? string.Empty]?.ShowShips();
}
private void ButtonDeleteObjectClick(object sender, EventArgs e)
{
if (listBoxStorage.SelectedIndex == -1)
{
return;
}
string name = listBoxStorage.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Delete Object {name}?", "Deleting",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(name);
ReloadObjects();
_logger.LogInformation($"Deleted set: {name}");
}
}
private void ButtonAddShip_Click(object sender, EventArgs e)
{
if (listBoxStorage.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorage.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
var formShipConfig = new FormShipConfig();
formShipConfig.Show();
formShipConfig.AddEvent(AddShip);
}
private void AddShip(DrawingShip ship)
{
if (listBoxStorage.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorage.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
try
{
_ = obj + ship;
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowShips();
_logger.LogInformation($"ship added in set {listBoxStorage.SelectedItem.ToString()}");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"ship not added in set {listBoxStorage.SelectedItem.ToString()}");
}
}
private void ButtonRemoveShip_Click(Object sender, EventArgs e)
{
if (listBoxStorage.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorage.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
if (MessageBox.Show("Delete Object?", "Delete", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
try
{
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos != null)
{
MessageBox.Show("Object deleted");
pictureBoxCollection.Image = obj.ShowShips();
_logger.LogInformation($"ship deleted in set {listBoxStorage.SelectedItem.ToString()}");
}
else
{
MessageBox.Show("Object not deleted");
_logger.LogWarning($"ship not deleted in set {listBoxStorage.SelectedItem.ToString()}");
}
}
catch (ShipNotFoundException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"ShipNotFound: {ex.Message} in set {listBoxStorage.SelectedItem.ToString()}");
}
catch (Exception ex)
{
MessageBox.Show("Not input");
_logger.LogWarning("Not input");
}
}
private void ButtonRefreshCollection(object sender, EventArgs e)
{
if (listBoxStorage.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorage.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
pictureBoxCollection.Image = obj.ShowShips();
}
private void SaveToolStripMenu_Click(object sender, EventArgs e)
{
if (SaveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.SaveData(SaveFileDialog.FileName);
MessageBox.Show("Saving complete", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"save in file {SaveFileDialog.FileName}");
}
catch (Exception ex)
{
MessageBox.Show($"Not saved: {ex.Message}", "Result", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Save to file {SaveFileDialog.FileName} not complete");
}
}
}
private void LoadToolStripMenu_Click(object sender, EventArgs args)
{
if (OpenFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_storage.LoadData(OpenFileDialog.FileName);
MessageBox.Show("Load complete", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadObjects();
_logger.LogInformation($"load from file {OpenFileDialog.FileName}");
}
catch (Exception ex)
{
MessageBox.Show($"Not loaded: {ex.Message}", "Result", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"load from file {OpenFileDialog.FileName} not complete");
}
}
}
}
}

View File

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

View File

@ -0,0 +1,360 @@
namespace ProjectWarmlyShip
{
partial class FormShipConfig
{
/// <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()
{
groupBoxParameters = new GroupBox();
labelAdvancedObject = new Label();
labelSimpleObject = new Label();
groupBoxColors = new GroupBox();
panelGray = new Panel();
panelWhite = new Panel();
panelPurple = new Panel();
panelBlack = new Panel();
panelYellow = new Panel();
panelGreen = new Panel();
panelRed = new Panel();
panelBlue = new Panel();
checkBoxFuelCompartment = new CheckBox();
checkBoxPipes = new CheckBox();
numericUpDownWeight = new NumericUpDown();
numericUpDownSpeed = new NumericUpDown();
labelWeight = new Label();
labelSpeed = new Label();
panelObject = new Panel();
labelMainColor = new Label();
labelOptionalColor = new Label();
pictureBoxObject = new PictureBox();
buttonAdd = new Button();
buttonCancel = new Button();
groupBoxParameters.SuspendLayout();
groupBoxColors.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).BeginInit();
panelObject.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBoxObject).BeginInit();
SuspendLayout();
//
// groupBoxParameters
//
groupBoxParameters.Controls.Add(labelAdvancedObject);
groupBoxParameters.Controls.Add(labelSimpleObject);
groupBoxParameters.Controls.Add(groupBoxColors);
groupBoxParameters.Controls.Add(checkBoxFuelCompartment);
groupBoxParameters.Controls.Add(checkBoxPipes);
groupBoxParameters.Controls.Add(numericUpDownWeight);
groupBoxParameters.Controls.Add(numericUpDownSpeed);
groupBoxParameters.Controls.Add(labelWeight);
groupBoxParameters.Controls.Add(labelSpeed);
groupBoxParameters.Location = new Point(10, 10);
groupBoxParameters.Name = "groupBoxParameters";
groupBoxParameters.Size = new Size(450, 220);
groupBoxParameters.TabIndex = 7;
groupBoxParameters.TabStop = false;
groupBoxParameters.Text = "Parameters";
//
// labelAdvancedObject
//
labelAdvancedObject.BorderStyle = BorderStyle.FixedSingle;
labelAdvancedObject.Font = new Font("Segoe UI", 15.75F, FontStyle.Regular, GraphicsUnit.Point);
labelAdvancedObject.Location = new Point(320, 173);
labelAdvancedObject.Name = "labelAdvancedObject";
labelAdvancedObject.Size = new Size(110, 35);
labelAdvancedObject.TabIndex = 8;
labelAdvancedObject.Text = "Advanced";
labelAdvancedObject.TextAlign = ContentAlignment.MiddleCenter;
labelAdvancedObject.MouseDown += LabelObject_MouseDown;
//
// labelSimpleObject
//
labelSimpleObject.BorderStyle = BorderStyle.FixedSingle;
labelSimpleObject.Font = new Font("Segoe UI", 15.75F, FontStyle.Regular, GraphicsUnit.Point);
labelSimpleObject.Location = new Point(200, 173);
labelSimpleObject.Name = "labelSimpleObject";
labelSimpleObject.Size = new Size(110, 35);
labelSimpleObject.TabIndex = 7;
labelSimpleObject.Text = "Simple";
labelSimpleObject.TextAlign = ContentAlignment.MiddleCenter;
labelSimpleObject.MouseDown += LabelObject_MouseDown;
//
// groupBoxColors
//
groupBoxColors.Controls.Add(panelGray);
groupBoxColors.Controls.Add(panelWhite);
groupBoxColors.Controls.Add(panelPurple);
groupBoxColors.Controls.Add(panelBlack);
groupBoxColors.Controls.Add(panelYellow);
groupBoxColors.Controls.Add(panelGreen);
groupBoxColors.Controls.Add(panelRed);
groupBoxColors.Controls.Add(panelBlue);
groupBoxColors.Location = new Point(200, 30);
groupBoxColors.Name = "groupBoxColors";
groupBoxColors.Size = new Size(230, 140);
groupBoxColors.TabIndex = 6;
groupBoxColors.TabStop = false;
groupBoxColors.Text = "Colors";
//
// panelGray
//
panelGray.BackColor = Color.Gray;
panelGray.Location = new Point(170, 80);
panelGray.Name = "panelGray";
panelGray.Size = new Size(50, 50);
panelGray.TabIndex = 1;
//
// panelWhite
//
panelWhite.BackColor = Color.White;
panelWhite.Location = new Point(115, 80);
panelWhite.Name = "panelWhite";
panelWhite.Size = new Size(50, 50);
panelWhite.TabIndex = 1;
//
// panelPurple
//
panelPurple.BackColor = Color.Purple;
panelPurple.Location = new Point(60, 80);
panelPurple.Name = "panelPurple";
panelPurple.Size = new Size(50, 50);
panelPurple.TabIndex = 2;
//
// panelBlack
//
panelBlack.BackColor = Color.Black;
panelBlack.Location = new Point(5, 80);
panelBlack.Name = "panelBlack";
panelBlack.Size = new Size(50, 50);
panelBlack.TabIndex = 1;
//
// panelYellow
//
panelYellow.BackColor = Color.Yellow;
panelYellow.Location = new Point(170, 20);
panelYellow.Name = "panelYellow";
panelYellow.Size = new Size(50, 50);
panelYellow.TabIndex = 1;
//
// panelGreen
//
panelGreen.BackColor = Color.Green;
panelGreen.Location = new Point(115, 20);
panelGreen.Name = "panelGreen";
panelGreen.Size = new Size(50, 50);
panelGreen.TabIndex = 1;
//
// panelRed
//
panelRed.BackColor = Color.Red;
panelRed.Location = new Point(60, 20);
panelRed.Name = "panelRed";
panelRed.Size = new Size(50, 50);
panelRed.TabIndex = 1;
//
// panelBlue
//
panelBlue.BackColor = Color.Blue;
panelBlue.Location = new Point(5, 20);
panelBlue.Name = "panelBlue";
panelBlue.Size = new Size(50, 50);
panelBlue.TabIndex = 0;
//
// checkBoxFuelCompartment
//
checkBoxFuelCompartment.AutoSize = true;
checkBoxFuelCompartment.Location = new Point(20, 145);
checkBoxFuelCompartment.Name = "checkBoxFuelCompartment";
checkBoxFuelCompartment.Size = new Size(124, 19);
checkBoxFuelCompartment.TabIndex = 5;
checkBoxFuelCompartment.Text = "Fuel compartment";
checkBoxFuelCompartment.UseVisualStyleBackColor = true;
//
// checkBoxPipes
//
checkBoxPipes.AutoSize = true;
checkBoxPipes.Location = new Point(20, 120);
checkBoxPipes.Name = "checkBoxPipes";
checkBoxPipes.Size = new Size(54, 19);
checkBoxPipes.TabIndex = 4;
checkBoxPipes.Text = "Pipes";
checkBoxPipes.UseVisualStyleBackColor = true;
//
// numericUpDownWeight
//
numericUpDownWeight.Location = new Point(75, 80);
numericUpDownWeight.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownWeight.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownWeight.Name = "numericUpDownWeight";
numericUpDownWeight.Size = new Size(120, 23);
numericUpDownWeight.TabIndex = 3;
numericUpDownWeight.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// numericUpDownSpeed
//
numericUpDownSpeed.Location = new Point(75, 40);
numericUpDownSpeed.Maximum = new decimal(new int[] { 1000, 0, 0, 0 });
numericUpDownSpeed.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
numericUpDownSpeed.Name = "numericUpDownSpeed";
numericUpDownSpeed.Size = new Size(120, 23);
numericUpDownSpeed.TabIndex = 2;
numericUpDownSpeed.Value = new decimal(new int[] { 100, 0, 0, 0 });
//
// labelWeight
//
labelWeight.AutoSize = true;
labelWeight.Location = new Point(20, 85);
labelWeight.Name = "labelWeight";
labelWeight.Size = new Size(48, 15);
labelWeight.TabIndex = 1;
labelWeight.Text = "Weight:";
//
// labelSpeed
//
labelSpeed.AutoSize = true;
labelSpeed.Location = new Point(20, 45);
labelSpeed.Name = "labelSpeed";
labelSpeed.Size = new Size(42, 15);
labelSpeed.TabIndex = 0;
labelSpeed.Text = "Speed:";
//
// panelObject
//
panelObject.AllowDrop = true;
panelObject.Controls.Add(labelMainColor);
panelObject.Controls.Add(labelOptionalColor);
panelObject.Controls.Add(pictureBoxObject);
panelObject.Location = new Point(465, 20);
panelObject.Name = "panelObject";
panelObject.Size = new Size(350, 180);
panelObject.TabIndex = 8;
panelObject.DragDrop += panelObject_DragDrop;
panelObject.DragEnter += PanelObject_DragEnter;
//
// labelMainColor
//
labelMainColor.AllowDrop = true;
labelMainColor.BorderStyle = BorderStyle.FixedSingle;
labelMainColor.Font = new Font("Segoe UI", 15.75F, FontStyle.Regular, GraphicsUnit.Point);
labelMainColor.Location = new Point(5, 0);
labelMainColor.Name = "labelMainColor";
labelMainColor.Size = new Size(165, 50);
labelMainColor.TabIndex = 10;
labelMainColor.Text = "Main Color";
labelMainColor.TextAlign = ContentAlignment.MiddleCenter;
labelMainColor.DragDrop += LabelMainColor_DragDrop;
labelMainColor.DragEnter += LabelColor_DragEnter;
//
// labelOptionalColor
//
labelOptionalColor.AllowDrop = true;
labelOptionalColor.BorderStyle = BorderStyle.FixedSingle;
labelOptionalColor.Font = new Font("Segoe UI", 15.75F, FontStyle.Regular, GraphicsUnit.Point);
labelOptionalColor.Location = new Point(180, 0);
labelOptionalColor.Name = "labelOptionalColor";
labelOptionalColor.Size = new Size(165, 50);
labelOptionalColor.TabIndex = 9;
labelOptionalColor.Text = "Optional Color";
labelOptionalColor.TextAlign = ContentAlignment.MiddleCenter;
labelOptionalColor.DragDrop += LabelOptionalColor_DragDrop;
labelOptionalColor.DragEnter += LabelColor_DragEnter;
//
// pictureBoxObject
//
pictureBoxObject.Location = new Point(5, 55);
pictureBoxObject.Name = "pictureBoxObject";
pictureBoxObject.Size = new Size(340, 120);
pictureBoxObject.TabIndex = 1;
pictureBoxObject.TabStop = false;
//
// buttonAdd
//
buttonAdd.Location = new Point(465, 205);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(170, 40);
buttonAdd.TabIndex = 9;
buttonAdd.Text = "Add";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += buttonAdd_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(645, 205);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(170, 40);
buttonCancel.TabIndex = 10;
buttonCancel.Text = "Cancel";
buttonCancel.UseVisualStyleBackColor = true;
//
// FormShipConfig
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(824, 251);
Controls.Add(buttonCancel);
Controls.Add(buttonAdd);
Controls.Add(panelObject);
Controls.Add(groupBoxParameters);
Name = "FormShipConfig";
Text = "FormShipConfig";
groupBoxParameters.ResumeLayout(false);
groupBoxParameters.PerformLayout();
groupBoxColors.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)numericUpDownWeight).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSpeed).EndInit();
panelObject.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)pictureBoxObject).EndInit();
ResumeLayout(false);
}
#endregion
private GroupBox groupBoxParameters;
private Label labelAdvancedObject;
private Label labelSimpleObject;
private GroupBox groupBoxColors;
private Panel panelGray;
private Panel panelWhite;
private Panel panelPurple;
private Panel panelBlack;
private Panel panelYellow;
private Panel panelGreen;
private Panel panelRed;
private Panel panelBlue;
private CheckBox checkBoxFuelCompartment;
private CheckBox checkBoxPipes;
private NumericUpDown numericUpDownWeight;
private NumericUpDown numericUpDownSpeed;
private Label labelWeight;
private Label labelSpeed;
private Panel panelObject;
private Label labelMainColor;
private Label labelOptionalColor;
private PictureBox pictureBoxObject;
private Button buttonAdd;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,133 @@
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 ProjectWarmlyShip.Entities;
using ProjectWarmlyShip.DrawingObjects;
using static System.Windows.Forms.DataFormats;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace ProjectWarmlyShip
{
public partial class FormShipConfig : Form
{
DrawingShip? _ship = null;
private event Action<DrawingShip> EventAddShip;
public FormShipConfig()
{
InitializeComponent();
panelBlack.MouseDown += PanelColor_MouseDown;
panelPurple.MouseDown += PanelColor_MouseDown;
panelGray.MouseDown += PanelColor_MouseDown;
panelGreen.MouseDown += PanelColor_MouseDown;
panelRed.MouseDown += PanelColor_MouseDown;
panelWhite.MouseDown += PanelColor_MouseDown;
panelYellow.MouseDown += PanelColor_MouseDown;
panelBlue.MouseDown += PanelColor_MouseDown;
buttonCancel.Click += (object sender, EventArgs a) => Close();
}
private void DrawShip()
{
Bitmap bmp = new(pictureBoxObject.Width, pictureBoxObject.Height);
Graphics gr = Graphics.FromImage(bmp);
_ship?.SetPosition(5, 5);
_ship?.DrawTrasport(gr);
pictureBoxObject.Image = bmp;
}
public void AddEvent(Action<DrawingShip> ev)
{
if (EventAddShip == null)
{
EventAddShip = ev;
}
else
{
EventAddShip += ev;
}
}
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)
{
ILogger<FormShipCollection> logger = new NullLogger<FormShipCollection>();
FormShipCollection form = new FormShipCollection(logger);
switch (e.Data?.GetData(DataFormats.Text).ToString())
{
case "labelSimpleObject":
labelOptionalColor.AllowDrop = false;
_ship = new DrawingShip((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White,
form.GetWidth(), form.GetHeight());
break;
case "labelAdvancedObject":
labelOptionalColor.AllowDrop = true;
_ship = new DrawingWarmlyShip((int)numericUpDownSpeed.Value,
(int)numericUpDownWeight.Value, Color.White, Color.Black,
checkBoxPipes.Checked, checkBoxFuelCompartment.Checked,
form.GetWidth(), form.GetHeight());
break;
}
DrawShip();
}
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)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void LabelMainColor_DragDrop(object sender, DragEventArgs e)
{
var color = e.Data.GetData(typeof(Color));
if (_ship != null && color != null)
{
_ship.EntityShip.MainColor = (Color)color;
DrawShip();
}
}
private void LabelOptionalColor_DragDrop(object sender, DragEventArgs e)
{
var color = e.Data.GetData(typeof(Color));
if (_ship != null && color != null && _ship.EntityShip is EntityWarmlyShip entityWarmlyShip)
{
entityWarmlyShip.OptionalColor = (Color)color;
DrawShip();
}
}
private void buttonAdd_Click(object sender, EventArgs e)
{
EventAddShip?.Invoke(_ship);
Close();
}
}
}

View File

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

View File

@ -0,0 +1,192 @@
namespace ProjectWarmlyShip
{
partial class WarmlyShipForm
{
/// <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()
{
pictureBoxWarmlyShip = new PictureBox();
buttonCreate = new Button();
buttonUp = new Button();
buttonDown = new Button();
buttonLeft = new Button();
buttonRight = new Button();
button1 = new Button();
comboBoxStrategy = new ComboBox();
buttonStep = new Button();
buttonSelectShip = new Button();
((System.ComponentModel.ISupportInitialize)pictureBoxWarmlyShip).BeginInit();
SuspendLayout();
//
// pictureBoxWarmlyShip
//
pictureBoxWarmlyShip.Dock = DockStyle.Fill;
pictureBoxWarmlyShip.Location = new Point(0, 0);
pictureBoxWarmlyShip.Name = "pictureBoxWarmlyShip";
pictureBoxWarmlyShip.Size = new Size(884, 461);
pictureBoxWarmlyShip.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBoxWarmlyShip.TabIndex = 0;
pictureBoxWarmlyShip.TabStop = false;
//
// buttonCreate
//
buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonCreate.Location = new Point(10, 425);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(75, 25);
buttonCreate.TabIndex = 1;
buttonCreate.Text = "Create Ship";
buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += ButtonCreateShip_Click;
//
// buttonUp
//
buttonUp.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonUp.BackgroundImage = Properties.Resources.ArrowUp;
buttonUp.BackgroundImageLayout = ImageLayout.Zoom;
buttonUp.Location = new Point(806, 383);
buttonUp.Name = "buttonUp";
buttonUp.Size = new Size(30, 30);
buttonUp.TabIndex = 2;
buttonUp.UseVisualStyleBackColor = true;
buttonUp.Click += buttonMove_Click;
//
// buttonDown
//
buttonDown.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonDown.BackgroundImage = Properties.Resources.ArrowDown;
buttonDown.BackgroundImageLayout = ImageLayout.Zoom;
buttonDown.Location = new Point(806, 419);
buttonDown.Name = "buttonDown";
buttonDown.Size = new Size(30, 30);
buttonDown.TabIndex = 3;
buttonDown.UseVisualStyleBackColor = true;
buttonDown.Click += buttonMove_Click;
//
// buttonLeft
//
buttonLeft.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonLeft.BackgroundImage = Properties.Resources.ArrowLeft;
buttonLeft.BackgroundImageLayout = ImageLayout.Zoom;
buttonLeft.Location = new Point(770, 419);
buttonLeft.Name = "buttonLeft";
buttonLeft.Size = new Size(30, 30);
buttonLeft.TabIndex = 4;
buttonLeft.UseVisualStyleBackColor = true;
buttonLeft.Click += buttonMove_Click;
//
// buttonRight
//
buttonRight.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonRight.BackgroundImage = Properties.Resources.ArrowRight;
buttonRight.BackgroundImageLayout = ImageLayout.Zoom;
buttonRight.Location = new Point(842, 419);
buttonRight.Name = "buttonRight";
buttonRight.Size = new Size(30, 30);
buttonRight.TabIndex = 5;
buttonRight.UseVisualStyleBackColor = true;
buttonRight.Click += buttonMove_Click;
//
// button1
//
button1.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
button1.Location = new Point(90, 425);
button1.Name = "button1";
button1.Size = new Size(120, 25);
button1.TabIndex = 6;
button1.Text = "Create Warmly Ship";
button1.UseVisualStyleBackColor = true;
button1.Click += ButtonCreateWarmlyShip_Click;
//
// comboBoxStrategy
//
comboBoxStrategy.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxStrategy.FormattingEnabled = true;
comboBoxStrategy.Items.AddRange(new object[] { "Move to center", "Move to border" });
comboBoxStrategy.Location = new Point(751, 12);
comboBoxStrategy.Name = "comboBoxStrategy";
comboBoxStrategy.Size = new Size(121, 23);
comboBoxStrategy.TabIndex = 7;
//
// buttonStep
//
buttonStep.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonStep.Location = new Point(797, 41);
buttonStep.Name = "buttonStep";
buttonStep.Size = new Size(75, 23);
buttonStep.TabIndex = 8;
buttonStep.Text = "Step";
buttonStep.UseVisualStyleBackColor = true;
buttonStep.Click += ButtonStep_Click;
//
// buttonSelectShip
//
buttonSelectShip.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonSelectShip.Location = new Point(215, 425);
buttonSelectShip.Name = "buttonSelectShip";
buttonSelectShip.Size = new Size(75, 25);
buttonSelectShip.TabIndex = 10;
buttonSelectShip.Text = "Select";
buttonSelectShip.UseVisualStyleBackColor = true;
buttonSelectShip.Click += ButtonSelectShip_Click;
//
// WarmlyShipForm
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(884, 461);
Controls.Add(buttonSelectShip);
Controls.Add(buttonStep);
Controls.Add(comboBoxStrategy);
Controls.Add(button1);
Controls.Add(buttonRight);
Controls.Add(buttonLeft);
Controls.Add(buttonDown);
Controls.Add(buttonUp);
Controls.Add(buttonCreate);
Controls.Add(pictureBoxWarmlyShip);
Name = "WarmlyShipForm";
StartPosition = FormStartPosition.CenterScreen;
Text = "WarmlyShip";
((System.ComponentModel.ISupportInitialize)pictureBoxWarmlyShip).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private PictureBox pictureBoxWarmlyShip;
private Button buttonCreate;
private Button buttonUp;
private Button buttonDown;
private Button buttonLeft;
private Button buttonRight;
private Button button1;
private ComboBox comboBoxStrategy;
private Button buttonStep;
private Button buttonSelectShip;
}
}

View File

@ -0,0 +1,140 @@
using ProjectWarmlyShip.DrawingObjects;
using ProjectWarmlyShip.MovementStrategy;
namespace ProjectWarmlyShip
{
public partial class WarmlyShipForm : Form
{
private DrawingShip? _drawingShip;
private AbstractStrategy? _abstractStrategy;
public DrawingShip SelectedShip { get; set; }
public WarmlyShipForm()
{
InitializeComponent();
_abstractStrategy = null;
SelectedShip = null;
}
private void Draw()
{
if (_drawingShip == null)
{
return;
}
Bitmap bmp = new(pictureBoxWarmlyShip.Width,
pictureBoxWarmlyShip.Height);
Graphics gr = Graphics.FromImage(bmp);
_drawingShip.DrawTrasport(gr);
pictureBoxWarmlyShip.Image = bmp;
}
private void ButtonCreateWarmlyShip_Click(object sender, EventArgs e)
{
Random random = new Random();
Color color = Color.FromArgb(random.Next(0, 256));
ColorDialog dialog = new ColorDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
Color opt_color = Color.FromArgb(random.Next(0, 256));
if (dialog.ShowDialog() == DialogResult.OK)
{
opt_color = dialog.Color;
}
_drawingShip = new DrawingWarmlyShip(
random.Next(100, 300), random.Next(1000, 3000),
color,
opt_color,
Convert.ToBoolean(random.Next(0, 2)),
Convert.ToBoolean(random.Next(0, 2)),
pictureBoxWarmlyShip.Width,
pictureBoxWarmlyShip.Height);
_drawingShip.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
private void ButtonCreateShip_Click(object sender, EventArgs e)
{
Random random = new Random();
Color color = Color.FromArgb(random.Next(0, 256));
ColorDialog dialog = new ColorDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
color = dialog.Color;
}
_drawingShip = new DrawingShip(
random.Next(100, 300),
random.Next(1000, 3000),
color,
pictureBoxWarmlyShip.Width,
pictureBoxWarmlyShip.Height);
_drawingShip.SetPosition(random.Next(10, 100), random.Next(10, 100));
Draw();
}
private void buttonMove_Click(object sender, EventArgs e)
{
if (_drawingShip == null)
{
return;
}
string name = ((Button)sender)?.Name ?? string.Empty;
switch (name)
{
case "buttonUp":
_drawingShip.MoveTransport(DirectionType.Up);
break;
case "buttonDown":
_drawingShip.MoveTransport(DirectionType.Down);
break;
case "buttonLeft":
_drawingShip.MoveTransport(DirectionType.Left);
break;
case "buttonRight":
_drawingShip.MoveTransport(DirectionType.Right);
break;
}
Draw();
}
private void ButtonStep_Click(object sender, EventArgs e)
{
if (_drawingShip == null)
{
return;
}
if (comboBoxStrategy.Enabled)
{
_abstractStrategy = comboBoxStrategy.SelectedIndex
switch
{
0 => new MoveToCenter(),
1 => new MoveToBorder(),
_ => null,
};
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.SetData(
new DrawingObjectShip(_drawingShip),
pictureBoxWarmlyShip.Width,
pictureBoxWarmlyShip.Height);
comboBoxStrategy.Enabled = false;
}
if (_abstractStrategy == null)
{
return;
}
_abstractStrategy.MakeStep();
Draw();
if (_abstractStrategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.Enabled = true;
_abstractStrategy = null;
}
}
private void ButtonSelectShip_Click(object sender, EventArgs e)
{
SelectedShip = _drawingShip;
DialogResult = DialogResult.OK;
}
}
}

View File

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

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectWarmlyShip.DrawingObjects;
namespace ProjectWarmlyShip.MovementStrategy
{
public interface IMoveableObject
{
ObjectParametrs? GetObjectPosition { get; }
int GetStep { get; }
bool CheckCanMove(DirectionType direction);
void MoveObject(DirectionType direction);
}
}

View File

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

View File

@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectWarmlyShip.MovementStrategy
{
public class MoveToCenter : AbstractStrategy
{
protected override bool IsTargetDestination()
{
var objParams = GetObjectParametrs;
if (objParams == null)
{
return false;
}
return
Math.Abs(objParams.ObjectMiddleHorizontal - FieldWidth / 2) <= GetStep()
&&
Math.Abs(objParams.ObjectMiddleVertical - FieldHeight / 2) <= GetStep();
}
protected override void MoveToTarget()
{
var objParams = GetObjectParametrs;
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,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectWarmlyShip.MovementStrategy
{
public class ObjectParametrs
{
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 => _x + _width;
public int DownBorder => _y + _height;
public int ObjectMiddleHorizontal => _x + _width / 2;
public int ObjectMiddleVertical => _y + _height / 2;
public ObjectParametrs(int x, int y, int width, int height)
{
_x = x;
_y = y;
_width = width;
_height = height;
}
}
}

View File

@ -0,0 +1,45 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using Serilog;
namespace ProjectWarmlyShip
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormShipCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormShipCollection>().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}appsettings.json", optional: false, reloadOnChange: true).Build();
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

View File

@ -0,0 +1,36 @@
<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.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.5" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
</Project>

View File

@ -0,0 +1,103 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ProjectWarmlyShip.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("ProjectWarmlyShip.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 ArrowDown {
get {
object obj = ResourceManager.GetObject("ArrowDown", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap ArrowLeft {
get {
object obj = ResourceManager.GetObject("ArrowLeft", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap ArrowRight {
get {
object obj = ResourceManager.GetObject("ArrowRight", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap ArrowUp {
get {
object obj = ResourceManager.GetObject("ArrowUp", 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="ArrowDown" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\ArrowDown.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="ArrowRight" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\ArrowRight.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="ArrowLeft" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\ArrowLeft.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="ArrowUp" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\ArrowUp.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.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

View File

@ -0,0 +1,81 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectWarmlyShip.Exceptions;
namespace ProjectWarmlyShip.Generics
{
internal class SetGeneric<T> where T : class
{
private readonly List<T?> _places;
public int Count => _places.Count;
private readonly int _maxCount;
public SetGeneric(int count)
{
_maxCount = count;
_places = new List<T?>(count);
}
public bool Insert(T ship)
{
return Insert(ship, 0);
}
public bool Insert(T ship, int position)
{
if (Count >= _maxCount)
{
throw new StorageOverflowException(_maxCount);
}
if (position < 0 || position >= _maxCount)
{
throw new StorageOverflowException("Impossible to insert");
}
_places.Insert(position, ship);
return true;
}
public bool Remove(int position)
{
if (position >= Count || position < 0)
{
throw new ShipNotFoundException("Invalid operation");
}
if (_places[position] == null)
{
throw new ShipNotFoundException(position);
}
_places.RemoveAt(position);
return true;
}
public T? this[int position]
{
get
{
if (position < 0 || position >= _places.Count)
{
return null;
}
return _places[position];
}
set
{
if (position < 0 || position >= _places.Count)
{
return;
}
_places[position] = value;
}
}
public IEnumerable<T?> GetShips(int? maxShips = null)
{
for (int i = 0; i < _places.Count; ++i)
{
yield return _places[i];
if (maxShips.HasValue && i == maxShips.Value)
{
yield break;
}
}
}
}
}

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectWarmlyShip.Exceptions
{
[Serializable]
internal class ShipNotFoundException : ApplicationException
{
public ShipNotFoundException(int i) : base($"Not found object on position {i}") { }
public ShipNotFoundException() : base() { }
public ShipNotFoundException(string message) : base(message) { }
public ShipNotFoundException(string message, Exception exception) : base(message, exception) { }
protected ShipNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

@ -0,0 +1,90 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectWarmlyShip.DrawingObjects;
using ProjectWarmlyShip.MovementStrategy;
namespace ProjectWarmlyShip.Generics
{
internal class ShipsGenericCollection<T, U>
where T : DrawingShip
where U : IMoveableObject
{
private readonly int _pictureWidth;
private readonly int _pictureHeight;
private readonly int _placeSizeWidth = 140;
private readonly int _placeSizeHeight = 80;
private readonly SetGeneric<T> _collection;
public ShipsGenericCollection(int picWidth, int picHeight)
{
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = new SetGeneric<T>(width * height);
}
public static bool operator +(ShipsGenericCollection<T, U> collect, T? obj)
{
if (obj == null)
{
return false;
}
return (bool)collect?._collection.Insert(obj);
}
public static T? operator -(ShipsGenericCollection<T, U> collect, int pos)
{
T? obj = collect._collection[pos];
if (obj != null)
{
collect._collection.Remove(pos);
}
return obj;
}
public U? GetU(int pos)
{
return (U?)_collection[pos]?.GetMoveableObject;
}
public Bitmap ShowShips()
{
Bitmap bmp = new(_pictureWidth, _pictureHeight);
Graphics gr = Graphics.FromImage(bmp);
DrawBackgroud(gr);
DrawObjects(gr);
return bmp;
}
private void DrawBackgroud(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 ship in _collection.GetShips())
{
if (ship != null)
{
ship.SetPosition((width - (i % width) - 1) * _placeSizeWidth, (i / height) * _placeSizeHeight + 15);
ship.DrawTrasport(g);
}
i++;
}
}
public IEnumerable<T?> GetShips => _collection.GetShips();
}
}

View File

@ -0,0 +1,140 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectWarmlyShip.MovementStrategy;
using ProjectWarmlyShip.DrawingObjects;
using ProjectWarmlyShip.Exceptions;
namespace ProjectWarmlyShip.Generics
{
internal class ShipsGenericStorage
{
readonly Dictionary<string, ShipsGenericCollection<DrawingShip, DrawingObjectShip>> _shipStorages;
public List<string> Keys => _shipStorages.Keys.ToList();
private readonly int _pictuteWidth;
private readonly int _pictuteHeight;
private static readonly char _separatorForKeyValue = '|';
private readonly char _separatorRecords = ';';
private static readonly char _separatorForObjects = ':';
public ShipsGenericStorage(int pictureWidth, int pictureHeight)
{
_shipStorages = new Dictionary<string, ShipsGenericCollection<DrawingShip, DrawingObjectShip>>();
_pictuteWidth = pictureWidth;
_pictuteHeight = pictureHeight;
}
public void AddSet(string name)
{
if (_shipStorages.ContainsKey(name))
{
return;
}
_shipStorages[name] = new ShipsGenericCollection<DrawingShip, DrawingObjectShip>(_pictuteWidth, _pictuteHeight);
}
public void DelSet(string name)
{
if (_shipStorages.ContainsKey(name))
{
_shipStorages.Remove(name);
}
}
public ShipsGenericCollection<DrawingShip, DrawingObjectShip>? this[string ind]
{
get
{
if (_shipStorages.ContainsKey(ind))
{
return _shipStorages[ind];
}
return null;
}
}
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
StringBuilder data = new();
foreach (KeyValuePair<string, ShipsGenericCollection<DrawingShip, DrawingObjectShip>> record in _shipStorages)
{
StringBuilder records = new();
foreach (DrawingShip? elem in record.Value.GetShips)
{
records.Append($"{elem?.GetDataForSave(_separatorForObjects)}{_separatorRecords}");
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
throw new ArgumentException("Invalid operation, there isn't any data");
}
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write($"ShipStorage{Environment.NewLine}{data}");
}
}
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("File not found");
}
string bufferTextFromFile = "";
using (StreamReader reader = new StreamReader(filename))
{
string str;
while ((str = reader.ReadLine()) != null)
{
bufferTextFromFile += str + '\r' + '\n';
}
}
var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' },
StringSplitOptions.RemoveEmptyEntries);
if (strs.Length == 0 || strs == null)
{
throw new ArgumentException("There isn't any data for load");
}
if (!strs[0].StartsWith("ShipStorage"))
{
throw new InvalidDataException("Invalid format of data");
}
_shipStorages.Clear();
foreach (string data in strs)
{
string[] record = data.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
continue;
}
ShipsGenericCollection<DrawingShip, DrawingObjectShip> collection = new(_pictuteWidth, _pictuteHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawingShip? ship = elem.CreateDrawingShip(_separatorForObjects, _pictuteWidth, _pictuteHeight);
if (ship != null)
{
if (!(collection + ship))
{
try
{
_ = collection + ship;
}
catch (ShipNotFoundException e)
{
throw e;
}
catch (StorageOverflowException e)
{
throw e;
}
}
}
}
_shipStorages.Add(record[0], collection);
}
}
}
}

View File

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

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectWarmlyShip.Exceptions
{
[Serializable]
internal class StorageOverflowException : ApplicationException
{
public StorageOverflowException(int count) : base($"There is exceeded a limit of allowed number: {count}") { }
public StorageOverflowException() : base() { }
public StorageOverflowException(string message) : base(message) { }
public StorageOverflowException(string message, Exception exception) : base(message, exception) { }
protected StorageOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}