diff options
-rw-r--r-- | .gitignore | 363 | ||||
-rw-r--r-- | .vscode/launch.json | 27 | ||||
-rw-r--r-- | .vscode/tasks.json | 42 | ||||
-rw-r--r-- | DotnetPgn.Test/DotnetPgn.Test.csproj | 26 | ||||
-rw-r--r-- | DotnetPgn.Test/PieceParserTest.cs | 17 | ||||
-rw-r--r-- | DotnetPgn.Test/TokenizerTest.cs | 82 | ||||
-rw-r--r-- | DotnetPgn.sln | 48 | ||||
-rw-r--r-- | DotnetPgn/DotnetPgn.csproj | 7 | ||||
-rw-r--r-- | DotnetPgn/Models/Enums.cs | 18 | ||||
-rw-r--r-- | DotnetPgn/Models/HalfMove.cs | 11 | ||||
-rw-r--r-- | DotnetPgn/Models/Square.cs | 22 | ||||
-rw-r--r-- | DotnetPgn/PieceParser.cs | 22 | ||||
-rw-r--r-- | DotnetPgn/Tokenizer.cs | 75 |
13 files changed, 760 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3524b8a --- /dev/null +++ b/.gitignore @@ -0,0 +1,363 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..6908dfa --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,27 @@ +{ + // Use IntelliSense to find out which attributes exist for C# debugging + // Use hover for the description of the existing attributes + // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md + "version": "0.2.0", + "configurations": [ + { + "name": ".NET Core Launch (console)", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "build", + // If you have changed target frameworks, make sure to update the program path. + "program": "${workspaceFolder}/DotnetPgn.Test/bin/Debug/net5.0/DotnetPgn.Test.dll", + "args": [], + "cwd": "${workspaceFolder}/DotnetPgn.Test", + // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console + "console": "internalConsole", + "stopAtEntry": false + }, + { + "name": ".NET Core Attach", + "type": "coreclr", + "request": "attach", + "processId": "${command:pickProcess}" + } + ] +}
\ No newline at end of file diff --git a/.vscode/tasks.json b/.vscode/tasks.json new file mode 100644 index 0000000..60924e5 --- /dev/null +++ b/.vscode/tasks.json @@ -0,0 +1,42 @@ +{ + "version": "2.0.0", + "tasks": [ + { + "label": "build", + "command": "dotnet", + "type": "process", + "args": [ + "build", + "${workspaceFolder}/DotnetPgn.Test/DotnetPgn.Test.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "publish", + "command": "dotnet", + "type": "process", + "args": [ + "publish", + "${workspaceFolder}/DotnetPgn.Test/DotnetPgn.Test.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "watch", + "command": "dotnet", + "type": "process", + "args": [ + "watch", + "run", + "${workspaceFolder}/DotnetPgn.Test/DotnetPgn.Test.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + } + ] +}
\ No newline at end of file diff --git a/DotnetPgn.Test/DotnetPgn.Test.csproj b/DotnetPgn.Test/DotnetPgn.Test.csproj new file mode 100644 index 0000000..0e90980 --- /dev/null +++ b/DotnetPgn.Test/DotnetPgn.Test.csproj @@ -0,0 +1,26 @@ +<Project Sdk="Microsoft.NET.Sdk">
+
+ <PropertyGroup>
+ <TargetFramework>net5.0</TargetFramework>
+
+ <IsPackable>false</IsPackable>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.7.1" />
+ <PackageReference Include="xunit" Version="2.4.1" />
+ <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
+ <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
+ <PrivateAssets>all</PrivateAssets>
+ </PackageReference>
+ <PackageReference Include="coverlet.collector" Version="1.3.0">
+ <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
+ <PrivateAssets>all</PrivateAssets>
+ </PackageReference>
+ </ItemGroup>
+
+ <ItemGroup> + <ProjectReference Include="..\DotnetPgn\DotnetPgn.csproj" /> + </ItemGroup>
+
+</Project>
diff --git a/DotnetPgn.Test/PieceParserTest.cs b/DotnetPgn.Test/PieceParserTest.cs new file mode 100644 index 0000000..e8aacf6 --- /dev/null +++ b/DotnetPgn.Test/PieceParserTest.cs @@ -0,0 +1,17 @@ +using System.Linq; +using DotnetPgn.Models; +using Xunit; + +namespace DotnetPgn.Test +{ + public class PieceParserTest + { + [Theory] + [InlineData("K", Piece.King)] + [InlineData("Q", Piece.Queen)] + public void ParsePieceTest(string input, Piece expectedOutput) + { + Assert.Equal(expectedOutput, PieceParser.ParsePiece(input)); + } + } +} diff --git a/DotnetPgn.Test/TokenizerTest.cs b/DotnetPgn.Test/TokenizerTest.cs new file mode 100644 index 0000000..cb9940b --- /dev/null +++ b/DotnetPgn.Test/TokenizerTest.cs @@ -0,0 +1,82 @@ +using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using DotnetPgn.Models;
+using Xunit;
+
+namespace DotnetPgn.Test
+{
+ public class TokenizerTest
+ {
+ [Fact]
+ public void ParseMovesTest()
+ {
+ var moveText = "1. e4 e5 2. Nf3 Qe7 3. d3 h5\n";
+ IEnumerable<HalfMove> halfmoves;
+
+ #region Expected
+ List<HalfMove> expectedHalfMoves = new()
+ {
+ new HalfMove
+ {
+ MoveNumber = 1,
+ Player = Player.White,
+ Piece = Piece.Pawn,
+ TargetSquare = new Square('e', 4),
+ },
+ new HalfMove
+ {
+ MoveNumber = 1,
+ Player = Player.Black,
+ Piece = Piece.Pawn,
+ TargetSquare = new Square('e', 5),
+ },
+ new HalfMove
+ {
+ MoveNumber = 2,
+ Player = Player.White,
+ Piece = Piece.Knight,
+ TargetSquare = new Square('f', 3),
+ },
+ new HalfMove
+ {
+ MoveNumber = 2,
+ Player = Player.Black,
+ Piece = Piece.Queen,
+ TargetSquare = new Square('e', 7),
+ },
+ new HalfMove
+ {
+ MoveNumber = 3,
+ Player = Player.White,
+ Piece = Piece.Pawn,
+ TargetSquare = new Square('d', 3),
+ },
+ new HalfMove
+ {
+ MoveNumber = 3,
+ Player = Player.Black,
+ Piece = Piece.Pawn,
+ TargetSquare = new Square('h', 5),
+ },
+ };
+ #endregion
+
+ halfmoves = Tokenizer.ParseMoves(moveText);
+
+ for (int i = 0; i < expectedHalfMoves.Count(); i++)
+ {
+ HalfMove generated = halfmoves.ElementAtOrDefault(i);
+ HalfMove expected = expectedHalfMoves.ElementAtOrDefault(i);
+
+ Assert.NotNull(generated);
+ Assert.NotNull(expected);
+ Assert.Equal(expected.MoveNumber, generated.MoveNumber);
+ Assert.Equal(expected.Player, generated.Player);
+ Assert.Equal(expected.Piece, generated.Piece);
+ Assert.Equal(expected.TargetSquare, generated.TargetSquare);
+ }
+ }
+ }
+}
diff --git a/DotnetPgn.sln b/DotnetPgn.sln new file mode 100644 index 0000000..53fe2ce --- /dev/null +++ b/DotnetPgn.sln @@ -0,0 +1,48 @@ +
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio 15
+VisualStudioVersion = 15.0.26124.0
+MinimumVisualStudioVersion = 15.0.26124.0
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotnetPgn", "DotnetPgn\DotnetPgn.csproj", "{94582A40-22EF-4884-A2CE-6F08E08776E8}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotnetPgn.Test", "DotnetPgn.Test\DotnetPgn.Test.csproj", "{F1ED5B4D-EC5B-4720-A877-B2CE895BD3B7}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Any CPU = Debug|Any CPU
+ Debug|x64 = Debug|x64
+ Debug|x86 = Debug|x86
+ Release|Any CPU = Release|Any CPU
+ Release|x64 = Release|x64
+ Release|x86 = Release|x86
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {94582A40-22EF-4884-A2CE-6F08E08776E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {94582A40-22EF-4884-A2CE-6F08E08776E8}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {94582A40-22EF-4884-A2CE-6F08E08776E8}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {94582A40-22EF-4884-A2CE-6F08E08776E8}.Debug|x64.Build.0 = Debug|Any CPU
+ {94582A40-22EF-4884-A2CE-6F08E08776E8}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {94582A40-22EF-4884-A2CE-6F08E08776E8}.Debug|x86.Build.0 = Debug|Any CPU
+ {94582A40-22EF-4884-A2CE-6F08E08776E8}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {94582A40-22EF-4884-A2CE-6F08E08776E8}.Release|Any CPU.Build.0 = Release|Any CPU
+ {94582A40-22EF-4884-A2CE-6F08E08776E8}.Release|x64.ActiveCfg = Release|Any CPU
+ {94582A40-22EF-4884-A2CE-6F08E08776E8}.Release|x64.Build.0 = Release|Any CPU
+ {94582A40-22EF-4884-A2CE-6F08E08776E8}.Release|x86.ActiveCfg = Release|Any CPU
+ {94582A40-22EF-4884-A2CE-6F08E08776E8}.Release|x86.Build.0 = Release|Any CPU
+ {F1ED5B4D-EC5B-4720-A877-B2CE895BD3B7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {F1ED5B4D-EC5B-4720-A877-B2CE895BD3B7}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {F1ED5B4D-EC5B-4720-A877-B2CE895BD3B7}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {F1ED5B4D-EC5B-4720-A877-B2CE895BD3B7}.Debug|x64.Build.0 = Debug|Any CPU
+ {F1ED5B4D-EC5B-4720-A877-B2CE895BD3B7}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {F1ED5B4D-EC5B-4720-A877-B2CE895BD3B7}.Debug|x86.Build.0 = Debug|Any CPU
+ {F1ED5B4D-EC5B-4720-A877-B2CE895BD3B7}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {F1ED5B4D-EC5B-4720-A877-B2CE895BD3B7}.Release|Any CPU.Build.0 = Release|Any CPU
+ {F1ED5B4D-EC5B-4720-A877-B2CE895BD3B7}.Release|x64.ActiveCfg = Release|Any CPU
+ {F1ED5B4D-EC5B-4720-A877-B2CE895BD3B7}.Release|x64.Build.0 = Release|Any CPU
+ {F1ED5B4D-EC5B-4720-A877-B2CE895BD3B7}.Release|x86.ActiveCfg = Release|Any CPU
+ {F1ED5B4D-EC5B-4720-A877-B2CE895BD3B7}.Release|x86.Build.0 = Release|Any CPU
+ EndGlobalSection
+EndGlobal
diff --git a/DotnetPgn/DotnetPgn.csproj b/DotnetPgn/DotnetPgn.csproj new file mode 100644 index 0000000..563e6f9 --- /dev/null +++ b/DotnetPgn/DotnetPgn.csproj @@ -0,0 +1,7 @@ +<Project Sdk="Microsoft.NET.Sdk">
+
+ <PropertyGroup>
+ <TargetFramework>net5.0</TargetFramework>
+ </PropertyGroup>
+
+</Project>
diff --git a/DotnetPgn/Models/Enums.cs b/DotnetPgn/Models/Enums.cs new file mode 100644 index 0000000..893f2fa --- /dev/null +++ b/DotnetPgn/Models/Enums.cs @@ -0,0 +1,18 @@ +namespace DotnetPgn.Models +{ + public enum Piece + { + Pawn, + Knight, + Bishop, + Rook, + Queen, + King, + } + + public enum Player + { + White, + Black, + } +}
\ No newline at end of file diff --git a/DotnetPgn/Models/HalfMove.cs b/DotnetPgn/Models/HalfMove.cs new file mode 100644 index 0000000..b94d77d --- /dev/null +++ b/DotnetPgn/Models/HalfMove.cs @@ -0,0 +1,11 @@ +namespace DotnetPgn.Models +{ + public record HalfMove + { + public int MoveNumber {get; init;} + public Player Player { get; init; } + public Piece Piece { get; init; } + public Square SourceSquare { get; init; } + public Square TargetSquare { get; init; } + } +}
\ No newline at end of file diff --git a/DotnetPgn/Models/Square.cs b/DotnetPgn/Models/Square.cs new file mode 100644 index 0000000..a3910d3 --- /dev/null +++ b/DotnetPgn/Models/Square.cs @@ -0,0 +1,22 @@ +using System; + +namespace DotnetPgn.Models +{ + public record Square + { + public char Rank { get; } + public int File { get; } + + public Square(char rank, int file) + { + if (rank < 'a' || rank > 'h') + throw new ArgumentException($"Invalid rank '{rank}'."); + + if (file < 1 || file > 8) + throw new ArgumentException($"Invalid file '{file}'."); + + Rank = rank; + File = file; + } + } +}
\ No newline at end of file diff --git a/DotnetPgn/PieceParser.cs b/DotnetPgn/PieceParser.cs new file mode 100644 index 0000000..5ea9402 --- /dev/null +++ b/DotnetPgn/PieceParser.cs @@ -0,0 +1,22 @@ +using System;
+using DotnetPgn.Models;
+
+namespace DotnetPgn
+{
+ public static class PieceParser
+ {
+ public static Piece ParsePiece(string sanPiece)
+ {
+ return sanPiece switch
+ {
+ "P" or "p" or "" => Piece.Pawn,
+ "N" or "n" => Piece.Knight,
+ "B" or "b" => Piece.Bishop,
+ "R" or "r" => Piece.Rook,
+ "Q" or "q" => Piece.Queen,
+ "K" or "k" => Piece.King,
+ _ => throw new ArgumentException($"'{sanPiece} is not a valid piece.'"),
+ };
+ }
+ }
+}
diff --git a/DotnetPgn/Tokenizer.cs b/DotnetPgn/Tokenizer.cs new file mode 100644 index 0000000..9f779cb --- /dev/null +++ b/DotnetPgn/Tokenizer.cs @@ -0,0 +1,75 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using DotnetPgn.Models; + +namespace DotnetPgn +{ + public static class Tokenizer + { + private static readonly Regex s_halfMoveRegex = + new(@"([KQRBNP]?)([a-h]?[1-8]?)(x?)([a-h][1-8])([+#]?)"); + + public static IEnumerable<HalfMove> ParseMoves(string moveText) + { + StringBuilder currToken = new(); + char[] moveTextChars = moveText.ToCharArray(); + int moveNumber = 1; + Player currPlayer = Player.White; + + for (int i = 0; i < moveTextChars.Length; i++) + { + char nextChar = moveTextChars[i]; + + if (nextChar is ' ' or '\t' or '\n' or '\r') + { + // We should have either a move number or a complete halfmove. + string token = currToken.ToString(); + currToken.Clear(); + Match match = s_halfMoveRegex.Match(token); + + if (!match.Success) + { + Console.WriteLine($"Unrecognized token: `{token}`"); + Console.WriteLine(); + continue; + } + + Console.WriteLine($"Recognized token: {token}"); + Console.WriteLine($"Matching groups: ({match.Groups[1].Value})" + + $"({match.Groups[2].Value})({match.Groups[3].Value})({match.Groups[4].Value})" + + $"({match.Groups[5].Value})"); + + var move = new HalfMove + { + MoveNumber = moveNumber, + Player = currPlayer, + Piece = PieceParser.ParsePiece(match.Groups[1].Value), + TargetSquare = new Square(match.Groups[4].Value[0], Convert.ToInt32(Char.GetNumericValue(match.Groups[4].Value[1]))), + }; + + Console.WriteLine($"Halfmove: {move.MoveNumber}. {move.Player} {move.Piece} from {move.SourceSquare} to {move.TargetSquare}"); + Console.WriteLine(); + + if (currPlayer == Player.White) + { + currPlayer = Player.Black; + } + else + { + currPlayer = Player.White; + moveNumber++; + } + + yield return move; + } + else + { + currToken.Append(nextChar); + } + } + } + } +}
\ No newline at end of file |