Пример #1
1
 private void MainWindow_Closed(object sender, System.EventArgs e)
 {
     ServiceLocator.Settings.OpenedFileName = ServiceLocator.GameTreeViewModel.FileName;
     var serializer = new SgfParser();
     ServiceLocator.Settings.CurrentGameSgf =
         Encoding.UTF8.GetString(serializer.Serialize(ServiceLocator.GameTreeViewModel.GameInfo));
     ServiceLocator.Settings.Save();
 }
Пример #2
0
    public void Escaped_property()
    {
        const string input    = @"(;A[\]b\nc\nd\t\te \n\]])";
        var          expected = TreeWithNoChildren(CreateData("A", @"]b c d  e  ]"));

        Assert.That(SgfParser.ParseTree(input), Is.EqualTo(expected).Using(SgfTreeEqualityComparer.Instance));
    }
Пример #3
0
        /// <summary>
        /// Creates a library item from file content info. Displays error info.
        /// </summary>
        /// <param name="fileInfo">File content info</param>
        /// <returns>Library item</returns>
        public async Task <LibraryItem> CreateLibraryItemFromFileContentAsync(FileContentInfo fileInfo)
        {
            if (fileInfo == null)
            {
                return(null);
            }
            var           parser     = new SgfParser();
            SgfCollection collection = null;

            try
            {
                collection = parser.Parse(fileInfo.Contents);
            }
            catch (SgfParseException e)
            {
                //ignore
                await _dialogService.ShowAsync(e.Message, Localizer.ErrorParsingSgfFile);
            }
            if (collection != null)
            {
                var newItem = CreateLibraryItem(fileInfo, collection);
                return(newItem);
            }
            return(null);
        }
Пример #4
0
    public void Node_without_properties()
    {
        var encoded  = "(;)";
        var expected = new SgfTree(new Dictionary <string, string[]>());

        AssertEqual(expected, SgfParser.ParseTree(encoded));
    }
Пример #5
0
        /// <summary>
        /// Creates a tsumego problem from the contents of an SGF file downloaded from online-go.com using
        /// the Ruby downloader.
        /// </summary>
        /// <param name="data">The contents of an SGF file.</param>
        /// <returns></returns>
        public static TsumegoProblem CreateFromSgfText(string data)
        {
            SgfParser   parser       = new SgfParser();
            var         collection   = parser.Parse(data);
            SgfGameTree sgfTree      = collection.GameTrees.First();
            string      problemName  = "";
            StoneColor  playerToPlay = StoneColor.None;

            foreach (var node in sgfTree.Sequence)
            {
                if (node["GN"] != null)
                {
                    problemName = node["GN"].Value <string>();
                }
                if (node["PL"] != null)
                {
                    SgfColor sgfColor = node["PL"].Value <SgfColor>();
                    switch (sgfColor)
                    {
                    case SgfColor.Black:
                        playerToPlay = StoneColor.Black;
                        break;

                    case SgfColor.White:
                        playerToPlay = StoneColor.White;
                        break;
                    }
                }
            }
            return(new TsumegoProblem(problemName, sgfTree, playerToPlay));
        }
Пример #6
0
    public void Two_nodes()
    {
        const string input    = "(;A[B];B[C])";
        var          expected = TreeWithSingleChild(CreateData("A", "B"), TreeWithNoChildren(CreateData("B", "C")));

        Assert.Equal(expected, SgfParser.ParseTree(input), SgfTreeEqualityComparer.Instance);
    }
Пример #7
0
    public void Multiple_properties()
    {
        const string input    = "(;A[b][c][d])";
        var          expected = TreeWithNoChildren(CreateData("A", "b", "c", "d"));

        Assert.Equal(expected, SgfParser.ParseTree(input), SgfTreeEqualityComparer.Instance);
    }
Пример #8
0
    public void Node_without_properties()
    {
        const string input    = "(;)";
        var          expected = TreeWithNoChildren(new Dictionary <string, string[]>());

        Assert.Equal(expected, SgfParser.ParseTree(input), SgfTreeEqualityComparer.Instance);
    }
Пример #9
0
    public void Escaped_property()
    {
        const string input    = @"(;A[\]b\nc\nd\t\te \n\]])";
        var          expected = TreeWithNoChildren(CreateData("A", "]b\nc\nd  e \n]"));

        Assert.Equal(expected, SgfParser.ParseTree(input), SgfTreeEqualityComparer.Instance);
    }
Пример #10
0
        public void AlphaGoGame3IsSuccessfullyParsed()
        {
            var parser     = new SgfParser();
            var collection = SgfTestHelpers.ParseFile(parser, "Valid/AlphaGo3.sgf");

            Assert.IsFalse(parser.HasWarnings);
        }
Пример #11
0
    public void Single_node_tree()
    {
        const string input    = "(;A[B])";
        var          expected = TreeWithNoChildren(CreateData("A", "B"));

        Assert.Equal(expected, SgfParser.ParseTree(input), SgfTreeEqualityComparer.Instance);
    }
Пример #12
0
        public void AlphaGoGame1IsSuccessfullyParsed()
        {
            var parser     = new SgfParser();
            var collection = SgfTestHelpers.ParseFile(parser, "Valid/AlphaGo1.sgf");

            //the file has one non-standard property - MULTIGOGM
            Assert.AreEqual(1, parser.Warnings.Count);
        }
Пример #13
0
    public void Single_node_tree()
    {
        var encoded  = "(;A[B])";
        var expected = new SgfTree(new Dictionary <string, string[]> {
            ["A"] = new[] { "B" }
        });

        AssertEqual(expected, SgfParser.ParseTree(encoded));
    }
Пример #14
0
    public void Escaped_property()
    {
        var encoded  = "(;A[\\]b\\nc\\nd\\t\\te \\n\\]])";
        var expected = new SgfTree(new Dictionary <string, string[]> {
            ["A"] = new[] { "]b\nc\nd  e \n]" }
        });

        AssertEqual(expected, SgfParser.ParseTree(encoded));
    }
Пример #15
0
        public void CollectionOfTwoMinimalGameTreesIsSuccessfullySerialized()
        {
            var targetSgf  = "(;)(;)";
            var parser     = new SgfParser();
            var collection = parser.Parse(targetSgf);
            var serialized = new SgfSerializer().Serialize(collection);

            Assert.AreEqual(targetSgf, serialized);
        }
Пример #16
0
    public void Multiple_properties()
    {
        var encoded  = "(;A[b]C[d])";
        var expected = new SgfTree(new Dictionary <string, string[]> {
            ["A"] = new[] { "b" }, ["C"] = new[] { "d" }
        });

        AssertEqual(expected, SgfParser.ParseTree(encoded));
    }
Пример #17
0
        private void AnalyzeGame(ExternalSgfFileViewModel libraryItem, LibraryItemGame game)
        {
            SgfParser parser        = new SgfParser();
            var       sgfCollection = parser.Parse(libraryItem.Contents);
            var       index         = Array.IndexOf(libraryItem.Games, game);
            var       sgfGameTree   = sgfCollection.GameTrees.ElementAt(index);

            StartAnalysis(libraryItem, sgfGameTree);
        }
Пример #18
0
    public void Multiple_property_values()
    {
        var encoded  = "(;A[b][c][d])";
        var expected = new SgfTree(new Dictionary <string, string[]> {
            ["A"] = new[] { "b", "c", "d" }
        });

        Assert.Equal(expected, SgfParser.ParseTree(encoded));
    }
Пример #19
0
        public void SimpleSgfInputIsSuccessfullySerialized()
        {
            var targetSgf =
                @"(;FF[4]C[root](;C[a];C[b](;C[c])(;C[d];C[e]))(;C[f](;C[g];C[h];C[i])(;C[j];LB[ab:Hello world!])))";
            var parser     = new SgfParser();
            var collection = parser.Parse(targetSgf);
            var serialized = new SgfSerializer().Serialize(collection);

            Assert.AreEqual(targetSgf, serialized);
        }
Пример #20
0
        public void MinimalGameTreeIsSuccessfullyParsed()
        {
            var parser     = new SgfParser();
            var collection = parser.Parse("(;)");

            Assert.IsFalse(parser.HasWarnings);
            Assert.AreEqual(1, collection.GameTrees.Count());
            Assert.AreEqual(1, collection.GameTrees.First().Sequence.Count());
            Assert.AreEqual(0, collection.GameTrees.First().Children.Count());
        }
Пример #21
0
    public void Two_nodes()
    {
        var encoded  = "(;A[B];B[C])";
        var expected = new SgfTree(new Dictionary <string, string[]> {
            ["A"] = new[] { "B" }
        }, new SgfTree(new Dictionary <string, string[]> {
            ["B"] = new[] { "C" }
        }));

        AssertEqual(expected, SgfParser.ParseTree(encoded));
    }
Пример #22
0
        public void SimpleSgfInputIsSuccessfullyParsed()
        {
            var parser     = new SgfParser();
            var collection = parser.Parse(@"(;FF[4]C[root](;C[a];C[b](;C[c])
(; C[ d ]; C[ e ]))
(; C[ f ](; C[ g ]; C[ h ]; C[ i ])
(; C[ j ])))
");

            Assert.IsFalse(parser.HasWarnings);
            Assert.AreEqual(1, collection.Count());
        }
Пример #23
0
        static void Main(string[] args)
        {
            SgfParser     sgfParser  = new SgfParser();
            SgfCollection collection = sgfParser.Parse(File.ReadAllText("S:\\DELETEME\\markup.sgf"));

            SgfToGameTreeConverter gameTreeConverter = new SgfToGameTreeConverter(collection.First());
            GameTreeNode           rootNode          = gameTreeConverter.Convert().GameTree.GameTreeRoot;

            //SgfParser.Deserialize(File.ReadAllText("C:\\Users\\Martin\\Downloads\\ff4_ex.sgf"));

            WriteMarkup(rootNode);
        }
Пример #24
0
    public void Two_child_trees()
    {
        const string input    = "(;A[B](;B[C])(;C[D]))";
        var          expected = TreeWithChildren(CreateData("A", "B"),
                                                 new[]
        {
            TreeWithNoChildren(CreateData("B", "C")),
            TreeWithNoChildren(CreateData("C", "D"))
        });

        Assert.Equal(expected, SgfParser.ParseTree(input), SgfTreeEqualityComparer.Instance);
    }
Пример #25
0
    public void Two_child_trees()
    {
        var encoded  = "(;A[B](;B[C])(;C[D]))";
        var expected = new SgfTree(new Dictionary <string, string[]> {
            ["A"] = new[] { "B" }
        }, new SgfTree(new Dictionary <string, string[]> {
            ["B"] = new[] { "C" }
        }), new SgfTree(new Dictionary <string, string[]> {
            ["C"] = new[] { "D" }
        }));

        AssertEqual(expected, SgfParser.ParseTree(encoded));
    }
Пример #26
0
        private async Task AnalyzeGameAsync(AppDataLibraryItemViewModel libraryItem, LibraryItemGame game)
        {
            //load from library
            LoadingText = Localizer.LoadingEllipsis;
            IsWorking   = true;

            var sgfContents = await _appDataFileService.ReadFileAsync(libraryItem.FileName, SgfFolderName);

            var parser      = new SgfParser();
            var collection  = parser.Parse(sgfContents);
            var index       = Array.IndexOf(libraryItem.Games, game);
            var sgfGameTree = collection.GameTrees.ElementAt(index);

            StartAnalysis(libraryItem, sgfGameTree);
            IsWorking = false;
        }
Пример #27
0
        /// <summary>
        /// Tests all files in an invalid folder for exceptions
        /// </summary>
        /// <param name="invalidFolder">Invalid SGF files folder</param>
        private void InvalidSgfFolderTest(string invalidFolder)
        {
            var parser = new SgfParser();
            var files  = SgfTestHelpers.GetSgfFiles(Path.Combine("Invalid", invalidFolder));

            foreach (var file in files)
            {
                try
                {
                    parser.Parse(File.ReadAllText(file));
                    Assert.Fail($"File {file} did not fail parsing");
                }
                catch (SgfParseException)
                {
                    //ok
                }
            }
        }
Пример #28
0
        public void ExampleSgfFileIsSuccessfullyParsed()
        {
            var parser     = new SgfParser();
            var collection = SgfTestHelpers.ParseFile(parser, "Valid/ff4_ex.sgf");

            //check the root game tree count
            Assert.AreEqual(2, collection.Count());

            var firstGameTree = collection.First();

            //check the game info properties
            Assert.AreEqual(1, firstGameTree.Sequence.Count());

            var rootNode = firstGameTree.Sequence.First();

            Assert.AreEqual("Gametree 1: properties", rootNode["GN"].Value <string>());

            var markupTree = firstGameTree.Children.ElementAt(2);

            Assert.AreEqual("Markup", markupTree.Sequence.First()["N"].Value <string>());
        }
Пример #29
0
 private LibraryItem RefreshLibraryItemBuilder(FileContentInfo fileContentInfo)
 {
     try
     {
         SgfParser parser        = new SgfParser();
         var       sgfCollection = parser.Parse(fileContentInfo.Contents);
         var       libraryItem   = CreateLibraryItem(fileContentInfo, sgfCollection);
         lock (_progressLock)
         {
             _loadedLibraryItems++;
         }
         return(libraryItem);
     }
     catch
     {
         //invalid item, ignore
         lock (_progressLock)
         {
             _loadedLibraryItems++;
         }
         return(null);
     }
 }
Пример #30
0
    public void Upper_and_lowercase_property()
    {
        var encoded = "(;Aa[b])";

        Assert.Throws <ArgumentException>(() => SgfParser.ParseTree(encoded));
    }
Пример #31
0
    public void Empty_input()
    {
        var encoded = "";

        Assert.Throws <ArgumentException>(() => SgfParser.ParseTree(encoded));
    }
Пример #32
0
        public GameInfo DetectFormatAndOpen(string fileUrlOrPath, out bool fromCache)
        {
            fileUrlOrPath = fileUrlOrPath.Trim();
            GameInfo result = null;
            long vkId;
            byte[] data = null;
            IDotsGameFormatParser parser = null;
            bool fromUrl = false;
            if (fileUrlOrPath.StartsWith("http://") || fileUrlOrPath.StartsWith("https://") ||
                long.TryParse(fileUrlOrPath, out vkId))
            {
                int digitPos = fileUrlOrPath.Length - 1;
                while (digitPos >= 0 && char.IsDigit(fileUrlOrPath[digitPos]))
                {
                    digitPos--;
                }
                digitPos++;
                vkId = long.Parse(fileUrlOrPath.Substring(digitPos));

                List<string> sgfUrls = new List<string>();
                if (fileUrlOrPath.Contains("/game/"))
                {
                    sgfUrls.Add(string.Format(VkPlaydotsSgfPrefix, "game", vkId));
                }
                else if (fileUrlOrPath.Contains("/practice/"))
                {
                    sgfUrls.Add(string.Format(VkPlaydotsSgfPrefix, "practice", vkId));
                }
                else
                {
                    sgfUrls.Add(string.Format(VkPlaydotsSgfPrefix, "game", vkId));
                    sgfUrls.Add(string.Format(VkPlaydotsSgfPrefix, "practice", vkId));
                }
                var webClient = new WebClient();
                webClient.Headers["Accept-Language"] = "en-US";
                Exception lastException = null;
                foreach (var sgfUrl in sgfUrls)
                {
                    try
                    {
                        data = webClient.DownloadData(sgfUrl);
                        if (Encoding.Default.GetString(data) != "An error occurred, it could not be saved in the format of sgf")
                        {
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        lastException = ex;
                    }
                }
                if (data == null)
                {
                    throw lastException;
                }
                parser = new SgfParser();
                fromUrl = true;
            }
            else if (Path.GetExtension(fileUrlOrPath) == ".sav")
            {
                parser = new PointsXtParser();
                data = File.ReadAllBytes(fileUrlOrPath);
            }
            else if (Path.GetExtension(fileUrlOrPath) == ".sgf")
            {
                parser = new SgfParser();
                data = File.ReadAllBytes(fileUrlOrPath);
            }
            else
            {
                throw new NotSupportedException($"Format of file {fileUrlOrPath} can not be detected or not supported");
            }

            string hash = CalculateHash(data);
            if (CachedGameInfo.Item1 != hash)
            {
                result = parser.Parse(data);
                result.FromUrl = fromUrl;
                CachedGameInfo = new Tuple<string, GameInfo>(hash, result);
                fromCache = false;
            }
            else
            {
                result = CachedGameInfo.Item2;
                fromCache = true;
            }

            return result;
        }