Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Заколюкин Степан #255

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cs/BowlingGame/BowlingGame.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
<PackageReference Include="FireSharp" Version="2.0.4" />
<PackageReference Include="FluentAssertions" Version="5.10.3" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.7.1" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="NUnit" Version="3.12.0" />
<PackageReference Include="NUnit.Console" Version="3.11.1" />
<PackageReference Include="NUnit3TestAdapter" Version="3.17.0" />
Expand Down
1 change: 1 addition & 0 deletions cs/Samples/Samples.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
<ItemGroup>
<PackageReference Include="FluentAssertions" Version="5.10.3" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.7.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="NUnit" Version="3.12.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.17.0" />
</ItemGroup>
Expand Down
23 changes: 23 additions & 0 deletions cs/TagsCloudVisualization/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using System.Drawing;
using TagsCloudVisualization.Task_2;


namespace TagsCloudVisualization;

internal class Program
{
private const string Path = "../../../../TagsCloudVisualization/Task 2";

static void Main()
{
var colors = new[] { Color.Red, Color.Green, Color.Brown, Color.Yellow, Color.Blue };

var visual = new VisualizationCloudLayout(800, 600, Color.White, colors);

visual.CreateImage(new CircularCloudLayouter(new Point(400, 300)), 175, new Size(30, 5), new Size(100, 25))
.Save($"{Path}/CentralСloud.png");

visual.CreateImage(new CircularCloudLayouter(new Point(250, 150)), 50, new Size(30, 5), new Size(80, 25))
.Save($"{Path}/SmalСloud.png");
}
}
19 changes: 19 additions & 0 deletions cs/TagsCloudVisualization/TagsCloudVisualization.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<GenerateProgramFile>false</GenerateProgramFile>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="FluentAssertions" Version="6.12.2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
<PackageReference Include="NUnit" Version="4.2.2" />
<PackageReference Include="NUnit3TestAdapter" Version="4.6.0" />
<PackageReference Include="System.Drawing.Common" Version="9.0.0" />
</ItemGroup>

</Project>
64 changes: 64 additions & 0 deletions cs/TagsCloudVisualization/Task 1,3/CircularCloudLayouter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
using System.Drawing;


namespace TagsCloudVisualization;

public class CircularCloudLayouter
{
private const double AngleChangeStep = Math.PI / 180;
private int DistanceBetweenTurns { get; set; }
private int InitialRadiusOfSpiral { get; set; }
private double AngleOfRotationInRadians { get; set; }

private readonly LinkedList<Rectangle> cloudOfRectangles;

public readonly Point Center;

public CircularCloudLayouter(Point center)
{
Center = center;
cloudOfRectangles = [];
DistanceBetweenTurns = 30;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Я не знаю почему это 30, наверное, стоит это вынести в конструктор чтобы абстрактный клиент мог это настроить

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вынести то можно, просто это значение потом все равно изменяется в методе PutNextRectangle в зависимости от самого маленького размера, который когда либо поступал в метод, это сделано для того чтобы увеличить кучность облака. Исходя из этого, я подумал, что наверное не будет смысла в возможности пользователя указать какое-то значение в конструкторе, т.к класс будет впоследствии его менять по определенному правилу

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ну я так понял оно будет меняться только в меньшую сторону, и, как ты сказал, оно влияет на кучность. Может, пользователь захочет облако побольше и чтобы между тегами было расстояние

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

как бы в целом, для решения задачи создания облака слов это справедливо, но если говорить конкретно об задаче из домашки, то там был такой критерий: "Облако должно быть плотным, чем плотнее, тем лучше."

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Пон, пусть тогда будет так

}

public Rectangle PutNextRectangle(Size rectangleSize)
{
var halfOfMinSide = Math.Min(rectangleSize.Width, rectangleSize.Height) / 2;
DistanceBetweenTurns = Math.Min(DistanceBetweenTurns, halfOfMinSide);

if (cloudOfRectangles.Count == 0) InitialRadiusOfSpiral = halfOfMinSide;

var rectangle = ChooseLocationForRectangle(rectangleSize);
cloudOfRectangles.AddFirst(rectangle);

return rectangle;
}

private Rectangle ChooseLocationForRectangle(Size rectangleSize)
{
var currentPoint = GetNewPoint();
var rectangle = GetNewRectangle(currentPoint, rectangleSize);

while (cloudOfRectangles.Any(rect => rect.IntersectsWith(rectangle)))
{
AngleOfRotationInRadians += AngleChangeStep;
currentPoint = GetNewPoint();
rectangle = GetNewRectangle(currentPoint, rectangleSize);
}

return rectangle;
}

private Rectangle GetNewRectangle(Point centerPoint, Size rectangleSize) =>
new(new(centerPoint.X - rectangleSize.Width / 2,
centerPoint.Y - rectangleSize.Height / 2), rectangleSize);

private Point GetNewPoint()
{
var coefficient = InitialRadiusOfSpiral + AngleOfRotationInRadians * DistanceBetweenTurns;
var x = coefficient * Math.Cos(AngleOfRotationInRadians) + Center.X;
var y = coefficient * Math.Sin(AngleOfRotationInRadians) + Center.Y;

return new((int)x, (int)y);
}
}
82 changes: 82 additions & 0 deletions cs/TagsCloudVisualization/Task 1,3/CircularCloudLayouterTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
using FluentAssertions;
using NUnit.Framework;
using NUnit.Framework.Interfaces;
using System.Drawing;
using TagsCloudVisualization.Task_2;


namespace TagsCloudVisualization;


[TestFixture]
public class CircularCloudLayouterTests
{
private readonly List<Rectangle> listRectangles = [];

[Test]
public void CircularCloudLayouter_CorrectInitialization_NoExceptions()
{
var createAConstructor = () => new CircularCloudLayouter(new Point(960, 540));

createAConstructor
.Should()
.NotThrow();
}

[Test]
public void PutNextRectangle_RandomSizes_MustBeRightSize()
{
var cloud = new CircularCloudLayouter(new Point(960, 540));
var random = new Random();

for (var i = 0; i < 50; i++)
{
var width = random.Next(30, 200);
var actualSize = new Size(width, random.Next(width / 6, width / 3));

var rectangle = cloud.PutNextRectangle(actualSize);

actualSize
.Should()
.Be(rectangle.Size);
}
}

[Test]
public void PutNextRectangle_RandomSizes_ShouldNotIntersect()
{
var cloudLayouter = new CircularCloudLayouter(new Point(960, 540));
var random = new Random();

for (int i = 0; i < 100; i++)
{
var width = random.Next(30, 200);

var rectangle = cloudLayouter.PutNextRectangle(new(width, random.Next(width / 6, width / 3)));

listRectangles.Any(rect => rect.IntersectsWith(rectangle))
.Should()
.BeFalse("Прямоугольники не должны пересекаться");

listRectangles.Add(rectangle);
}
}

[TearDown]
public void CreateReportInCaseOfAnError()
{
if (TestContext.CurrentContext.Result.Outcome == ResultState.Failure)
{
var colors = new[] { Color.Red, Color.Green, Color.Brown, Color.Yellow, Color.Blue };
var path = "../../../../TagsCloudVisualization/TestErrorReports/сloud.png";
var visual = new VisualizationCloudLayout(1920, 1080, Color.White, colors);

visual.CreateImage(listRectangles)
.Save(path);

Console.WriteLine($"Tag cloud visualization saved to file {Path.GetFullPath(path)}");
}

listRectangles.Clear();
}
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
33 changes: 33 additions & 0 deletions cs/TagsCloudVisualization/Task 2/CloudLayout.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
using System.Drawing;

namespace TagsCloudVisualization.Task_2;

public static class CloudLayout
{
public static IEnumerable<Rectangle> GenerateCloudLayout(
int amountRectangles,
Size minSize,
Size maxSize,
CircularCloudLayouter cloudLayouter)
=> GenerateRectangleSizes(amountRectangles, minSize, maxSize)
.Select(cloudLayouter.PutNextRectangle);

private static IEnumerable<Size> GenerateRectangleSizes(
int amountData,
Size minSize,
Size maxSize)
{
if (minSize.Width > maxSize.Width || minSize.Height > maxSize.Width)
throw new ArgumentException("Минимальные размеры не могут быть больше максимальных");

var random = new Random();

for (var i = 0; i < amountData; i++)
{
var width = random.Next(minSize.Width, maxSize.Width + 1);
var height = random.Next(minSize.Height, maxSize.Height + 1);

yield return new Size(width, height);
}
}
}
4 changes: 4 additions & 0 deletions cs/TagsCloudVisualization/Task 2/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Раскладка 1
![CentralСloud](CentralСloud.png)
Раскладка 2
![SmalСloud](SmalСloud.png)
Binary file added cs/TagsCloudVisualization/Task 2/SmalСloud.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
59 changes: 59 additions & 0 deletions cs/TagsCloudVisualization/Task 2/VisualizationCloudLayout.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
using Newtonsoft.Json.Linq;
using System.Drawing;

namespace TagsCloudVisualization.Task_2;

public class VisualizationCloudLayout
{
private readonly int width;
private readonly int height;
private readonly Color backgroundColor;
private readonly Color[] rectanglePalette;

public VisualizationCloudLayout(int width, int height, Color backgroundColor, IEnumerable<Color> rectanglePalette)
{
this.width = width;
this.height = height;
this.backgroundColor = backgroundColor;
this.rectanglePalette = rectanglePalette.ToArray();
}

public Bitmap CreateImage(CircularCloudLayouter cloudLayouter, int amountRectangles,
Size minSize, Size maxSize)
{
var image = new Bitmap(width, height);
var rectangles = CloudLayout.GenerateCloudLayout(
amountRectangles,
minSize,
maxSize,
cloudLayouter);

DrawCloudLayout(Graphics.FromImage(image), rectangles);

return image;
}

public Bitmap CreateImage(IEnumerable<Rectangle> rectangles)
{
var image = new Bitmap(width, height);

DrawCloudLayout(Graphics.FromImage(image), rectangles);

return image;
}

private void DrawCloudLayout(Graphics graphics, IEnumerable<Rectangle> rectangles)
{
var random = new Random();

graphics.FillRectangle(new SolidBrush(backgroundColor), 0, 0, width, height);

foreach (var rect in rectangles)
{
var color = rectanglePalette[random.Next(rectanglePalette.Length)];

graphics.FillRectangle(new SolidBrush(color), rect);
graphics.DrawRectangle(new Pen(Color.Black, 1), rect);
}
}
}
17 changes: 13 additions & 4 deletions cs/tdd.sln
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25123.0
# Visual Studio Version 17
VisualStudioVersion = 17.11.35312.102
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BowlingGame", "BowlingGame\BowlingGame.csproj", "{AD0F018A-732E-4074-8527-AB2EEC8D0BF3}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BowlingGame", "BowlingGame\BowlingGame.csproj", "{AD0F018A-732E-4074-8527-AB2EEC8D0BF3}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Samples", "Samples\Samples.csproj", "{B5108E20-2ACF-4ED9-84FE-2A718050FC94}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Samples", "Samples\Samples.csproj", "{B5108E20-2ACF-4ED9-84FE-2A718050FC94}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TagsCloudVisualization", "TagsCloudVisualization\TagsCloudVisualization.csproj", "{1C4D8E05-ABDC-43A6-BFBA-741A8435AF31}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Expand All @@ -21,8 +23,15 @@ Global
{B5108E20-2ACF-4ED9-84FE-2A718050FC94}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B5108E20-2ACF-4ED9-84FE-2A718050FC94}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B5108E20-2ACF-4ED9-84FE-2A718050FC94}.Release|Any CPU.Build.0 = Release|Any CPU
{1C4D8E05-ABDC-43A6-BFBA-741A8435AF31}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1C4D8E05-ABDC-43A6-BFBA-741A8435AF31}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1C4D8E05-ABDC-43A6-BFBA-741A8435AF31}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1C4D8E05-ABDC-43A6-BFBA-741A8435AF31}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {460B15EA-8A79-4B9D-AE55-4F1224612C1D}
EndGlobalSection
EndGlobal
3 changes: 3 additions & 0 deletions cs/tdd.sln.DotSettings
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=PrivateInstanceFields/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=TypesAndNamespaces/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="AaBb_AaBb" /&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/UserRules/=4a98fdf6_002D7d98_002D4f5a_002Dafeb_002Dea44ad98c70c/@EntryIndexedValue">&lt;Policy&gt;&lt;Descriptor Staticness="Instance" AccessRightKinds="Private" Description="Instance fields (private)"&gt;&lt;ElementKinds&gt;&lt;Kind Name="FIELD" /&gt;&lt;Kind Name="READONLY_FIELD" /&gt;&lt;/ElementKinds&gt;&lt;/Descriptor&gt;&lt;Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /&gt;&lt;/Policy&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/UserRules/=a0b4bc4d_002Dd13b_002D4a37_002Db37e_002Dc9c6864e4302/@EntryIndexedValue">&lt;Policy&gt;&lt;Descriptor Staticness="Any" AccessRightKinds="Any" Description="Types and namespaces"&gt;&lt;ElementKinds&gt;&lt;Kind Name="NAMESPACE" /&gt;&lt;Kind Name="CLASS" /&gt;&lt;Kind Name="STRUCT" /&gt;&lt;Kind Name="ENUM" /&gt;&lt;Kind Name="DELEGATE" /&gt;&lt;/ElementKinds&gt;&lt;/Descriptor&gt;&lt;Policy Inspect="True" Prefix="" Suffix="" Style="AaBb_AaBb" /&gt;&lt;/Policy&gt;</s:String>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EPredefinedNamingRulesToUserRulesUpgrade/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/PatternsAndTemplates/LiveTemplates/Template/=13FAEF5AD10371439A650EAFEB60E612/@KeyIndexDefined">True</s:Boolean>
<s:Boolean x:Key="/Default/PatternsAndTemplates/LiveTemplates/Template/=13FAEF5AD10371439A650EAFEB60E612/Applicability/=Live/@EntryIndexedValue">True</s:Boolean>
<s:String x:Key="/Default/PatternsAndTemplates/LiveTemplates/Template/=13FAEF5AD10371439A650EAFEB60E612/Categories/=Imported_002010_002E10_002E2016/@EntryIndexedValue">Imported 10.10.2016</s:String>
Expand Down