Пример #1
0
        public void CanParseMapPackSize()
        {
            var p    = new MapParser(PoEItemData.Map.MAP_MAGIC);
            var item = p.Parse();

            Assert.AreEqual(12, item.PackSize);
        }
Пример #2
0
 public void ParsesAllRealMaps()
 {
     foreach (var mapFile in Directory.EnumerateFiles(@"..\..\..\..\Data\maps", "*.desc"))
     {
         MapParser.Parse(File.ReadAllText(mapFile), string.Empty);
     }
 }
Пример #3
0
        public void CanParseMapItemRarity()
        {
            var p    = new MapParser(PoEItemData.Map.MAP_MAGIC);
            var item = p.Parse();

            Assert.AreEqual(19, item.ItemRarity);
        }
Пример #4
0
        public void CanParseMapTier()
        {
            var p    = new MapParser(PoEItemData.Map.MAP_MAGIC);
            var item = p.Parse();

            Assert.AreEqual(1, item.Tier);
        }
Пример #5
0
    // Map Operations

    public void OpenMap(string path = null)
    {
        if (path == null)
        {
            // show a file dialog
            string[] paths = StandaloneFileBrowser.OpenFilePanel("Open Map", "", OpenMapExtensions, false);
            // make sure a file was selected
            if (paths.Length > 0)
            {
                path = paths[0];
                mapStopwatch.Start();
                Map mapToLoad = MapParser.Parse(paths[0]); // load the selected file
                mapStopwatch.Stop();
                UnityEngine.Debug.Log($"Parsed {mapToLoad.Bricks.Count} bricks in " + mapStopwatch.ElapsedMilliseconds + " ms");

                LoadMap(mapToLoad);
            }
        }
        else
        {
            mapStopwatch.Start();
            Map mapToLoad = MapParser.Parse(path); // load the selected file
            mapStopwatch.Stop();
            UnityEngine.Debug.Log($"Parsed {mapToLoad.Bricks.Count} bricks in " + mapStopwatch.ElapsedMilliseconds + " ms");

            LoadMap(mapToLoad);
        }

        FileHistoryManager.AddToRecents(path);
    }
Пример #6
0
    private void Start()
    {
        // check command args
        string[] args = Environment.GetCommandLineArgs();
        for (int i = 0; i < args.Length; i++)
        {
            try {
                string extension = Path.GetExtension(args[i]).ToLower();
                if (extension == ".brk")
                {
                    Map chosenMap = MapParser.Parse(args[i]);
                    LoadMap(chosenMap);
                    break;
                }
            } catch (Exception e) {
                // not epic
                UnityEngine.Debug.LogException(e);
                continue;
            }
        }

        // autosave
        InvokeRepeating("Autosave", SettingsManager.Settings.AutosaveRate * 60, SettingsManager.Settings.AutosaveRate * 60);

        //rp
        if (!MapIsLoaded)
        {
            SetRichPresence("Staring at the main menu", "icon", "BrickBuilder Icon");
        }
    }
Пример #7
0
 public void MapParserTest()
 {
     var chars = new List<char>();
     var p0 = new RangeParser<char>('A', 'Z');
     var mapParser = new MapParser<char, char, char, string>(
         p0, p0,
         (ch0, ch1) => new string(new[] {ch0, ch1}));
     int endInput;
     string result;
     mapParser.Parse(chars, 0, out endInput, out result).IsFalse();
     chars.Add('A');
     mapParser.Parse(chars,0, out endInput,out result).IsFalse();
     chars.Add('Z');
     mapParser.Parse(chars,0, out endInput, out result).IsTrue();
     result.Is("AZ");
 }
Пример #8
0
        public void CanCalcDists()
        {
            var map   = MapParser.Parse(File.ReadAllText("../../../../Data/maps/prob-067.desc"), string.Empty);
            var dists = new DistsFromCenter(new State(map));
            var bmp   = dists.SaveToBitmap();

            bmp.Save("../../../../prob.png");
        }
Пример #9
0
        public void CanParseItemInfo()
        {
            var p    = new MapParser(PoEItemData.Map.MAP_NORMAL);
            var item = p.Parse();

            Assert.AreEqual(Rarity.Normal, item.Rarity);
            Assert.AreEqual("Fungal Hollow Map", item.Base);
        }
    // Use this for initialization
    void Start()
    {
        float[] xx = new float[6] {
            0, 9, 9, 0, -9, -9
        };
        float[] zz = new float[6] {
            10.392f, 5.196f, -5.196f, -10.392f, -5.196f, 5.196f
        };
        float x = 0.0f, z = 0.0f;

        parser = GameObject.Find("MapParser").GetComponent <MapParser>();
        DS MapData = parser.data;

        parser.Parse();

        GameObject obj = GameObject.Find("tile");
        GameObject tile;

        for (int area = 0; area < MapData.Areas; area++)
        {
            if (area != 0)
            {
                tile = Instantiate(obj, new Vector3(obj.transform.position.x + x, obj.transform.position.y, obj.transform.position.z + z), Quaternion.identity);

                tile.GetComponentInChildren <MeshRenderer>().material = (UnityEngine.Material)Resources.Load("Tile Material " + MapData.map[area].tile[0].material_num.ToString());
            }
            for (int i = 0; i < 6; i++)
            {
                if (MapData.map[area].tile[i].enable)
                {
                    tile = Instantiate(obj, new Vector3(obj.transform.position.x + x + xx[i], obj.transform.position.y, obj.transform.position.z + z + zz[i]), Quaternion.identity);

                    tile.GetComponentInChildren <MeshRenderer>().material = (UnityEngine.Material)Resources.Load("Tile Material " + MapData.map[area].tile[i].material_num.ToString());
                }
            }

            if (area < MapData.Areas - 1)
            {
                x += xx[MapData.map[area].nextArea - 1] * 3;
                z += zz[MapData.map[area].nextArea - 1] * 3;
            }
        }

        for (int i = 0; i < 6; i++)
        {
            GameObject curwall = GameObject.Find("FW" + i);
            curwall.transform.position           = new Vector3(0.0f + x + xx[i] / 2, 4.0f, 0.0f + z + zz[i] / 2);
            curwall.GetComponent <Rotate>().goal = 1;
            if (i % 3 == 1)
            {
                curwall.transform.RotateAround(curwall.transform.position, Vector3.up, 60.0f);
            }
            else if (i % 3 == 2)
            {
                curwall.transform.RotateAround(curwall.transform.position, Vector3.up, -60.0f);
            }
        }
    }
Пример #11
0
        public Map Load(TextAsset asset)
        {
            if (asset == null)
            {
                throw new UnityException("Must set Map data as text asset.");
            }

            return(parser.Parse(asset.text));
        }
Пример #12
0
        public void CanParseModdableItemSections()
        {
            var p    = new MapParser(PoEItemData.Map.MAP_MAGIC);
            var item = p.Parse();

            Assert.AreEqual(63, item.ItemLevel);
            Assert.AreEqual("Monsters fire 2 additional Projectiles", item.ExplicitMods[0].ToString());
            Assert.AreEqual("Monsters gain an Endurance Charge on Hit", item.ExplicitMods[1].ToString());
        }
Пример #13
0
        public void CloningSampleSolutionIsValid()
        {
            var map      = MapParser.Parse("(0,0),(10,0),(10,10),(0,10)#(0,0)#(4,2),(6,2),(6,7),(4,7);(5,8),(6,8),(6,9),(5,9)#B(0,1);F(0,2);L(0,3);R(0,4);C(0,5);C(0,6);C(0,7);X(0,9)", string.Empty);
            var commands = CommandsSerializer.Parse("WWWWWWWWWCDDDDDDESSSSSS#CDDDDDDDDESSSSSSSS#CSSDDDESSSSS#ESSSSSSSSSQDDDDD");
            var solution = Emulator.MakeExtendedSolution(map, "test", commands, string.Empty);

            Assert.True(solution.IsSuccessful);
            Assert.Equal(28, solution.TimeUnits);
        }
        public Maze Read(StreamReader stream)
        {
            var mapTokinizer = new MapTokinizer();

            Tokenizers.Models.MapTokens mapTokens = mapTokinizer.ReadMapTokens(stream);


            var  mapParser = new MapParser();
            Maze map       = mapParser.Parse(mapTokens);

            return(map);
        }
Пример #15
0
    public void WhichStage(int n)
    {
        GameManager.I.stage = n;

        MapParser parser = GameObject.Find("MapParser").GetComponent <MapParser>();

        GameObject.Find("StageNum").GetComponent <Text>().text = n.ToString();

        DS MapData = parser.data;

        parser.Parse();
        GameObject.Find("Limit").GetComponent <Text>().text = MapData.Count.ToString();
        GameManager.I.count = MapData.Count;
    }
Пример #16
0
        public void TestMap001()
        {
            var mapContent  = File.ReadAllText(@"..\..\..\..\Data\maps\prob-001.desc");
            var map         = MapParser.Parse(mapContent, string.Empty);
            var expectedMap = @"
xxxxxxxxxx
x......xxx
x........x
xv.....xxx
xxxxxxxxxx
".Trim();

            Assert.Equal(expectedMap.Replace("\r\n", "\n"), map.ToString());
        }
 private void MainWindowLoad(object sender, EventArgs e)
 {
     try
     {
         Flush();
         if (CurrentMapFile != null)
         {
             AddMap(MapParser.Parse(CurrentMapFile));
         }
     }
     catch (Exception ex)
     {
         ExceptionDialog.Show(this, ex);
     }
 }
Пример #18
0
        static void Main(string[] args)
        {
            string map    = args[0];
            string output = args[1];

            var mapParser = new MapParser(map);
            var json      = mapParser.Parse();

            if (File.Exists(output))
            {
                File.Delete(output);
            }

            File.WriteAllText(output, json);
            Console.WriteLine("Job's done!");
        }
        public Map LoadMap()
        {
            var openFileDialog = new OpenFileDialog
            {
                DefaultExt = ".xml",
                Filter     = Resources.MapFileFilter
            };

            if (openFileDialog.ShowDialog() == DialogResult.Cancel)
            {
                return(null);
            }
            var map = MapParser.Parse(openFileDialog.FileName);

            CurrentMapFile = openFileDialog.FileName;
            StatusBarMessage("Map loaded.");
            return(map);
        }
Пример #20
0
        public void send_map_confirmation(String mapName, String serverKey)
        {
            currentMapName = mapName;

            try
            {
                mappie = new MapParser(mapName);
                mappie.Parse();
                String fullMapDirectory = Directory.GetCurrentDirectory() + "\\maps\\" + mapName + ".map";
                LogConsole("Map directory: " + fullMapDirectory);
                BinaryReader binReader = new BinaryReader(
                    new FileStream(fullMapDirectory, FileMode.Open));

                botLogics.AddPathFinder();


                byte[] bMap = binReader.ReadBytes(Convert.ToInt32(binReader.BaseStream.Length));
                int    sum  = 0;
                for (int i = 0; i < bMap.Length; i++)
                {
                    sum += (byte)bMap[i];
                }

                binReader.Close();

                PacketStream ps = new PacketStream();
                ps.WriteShort(packetNumber); ps.WriteByte(0xfc); ps.WriteByte(0x03);
                ps.WriteString(bMap.Length.ToString() + "|" + sum.ToString());
                byte[] hash = MapHasher.MapHash(serverKey);

                ps.WriteByte(10);
                for (int i = 0; i < 10; i++)
                {
                    ps.WriteByte(hash[i]);
                }
                ps.WriteByte(6);
                ch.SendStream(ps, true);
            }
            catch (Exception ex)
            {
                LogConsole(ex.Message);
            }
        }
Пример #21
0
 private void InitMap()
 {
     try
     {
         if (Calibration.Initialized)
         {
             Map = MapParser.Parse(Calibration.Instance.GetRecord <string>("MapFile"));
         }
         else
         {
             Map = MapParser.Parse("../resources/maps/testmaze.map");
         }
     }
     catch (Exception e)
     {
         Logger.Log(e.GetType().Name + " " + e.Message + " at line " + MapParser.CurrentLineNr);
         Logger.Log(this, "Map parsing failed: Exit in 5 seconds.");
         System.Threading.Thread.Sleep(5000);
         Environment.Exit(-1);
     }
 }
Пример #22
0
        public void RunDifferentBfs()
        {
            var map = MapParser.Parse(File.ReadAllText("../../../../Data/maps/prob-142.desc"), string.Empty);

            void Measure(IStrategy strat)
            {
                var solution = Emulator.MakeExtendedSolution(map, strat, string.Empty);

                File.WriteAllText($"../../../../Data/prob-142-{solution.StrategyName}.sol", solution.Commands);
                this.testOutputHelper.WriteLine($"{strat.Name}: {solution.TimeUnits}");
            }

            Measure(new DumbBfs());
            Measure(new DumbBfs(false));
            Measure(new DumbLookAheadBfs(0));
            Measure(new DumbLookAheadBfs(1));
            Measure(new DumbLookAheadBfs(2));
            Measure(new DumbLookAheadBfs(3));

            // Measure(new DumbLookAheadBfs(10));
        }
Пример #23
0
        public void TestParseExampleMap()
        {
            const string ExampleMap = "(0,0),(10,0),(10,10),(0,10)#(0,0)#(4,2),(6,2),(6,7),(4,7);(5,8),(6,8),(6,9),(5,9)#B(0,1);B(1,1);F(0,2);F(1,2);L(0,3);X(0,9)";
            var          map        = MapParser.Parse(ExampleMap, string.Empty);

            var expectedMap = @"
xxxxxxxxxxxx
xX.........x
x.....#....x
x..........x
x....##....x
x....##....x
x....##....x
xL...##....x
xFF..##....x
xBB........x
xv.........x
xxxxxxxxxxxx
".Trim();

            Assert.Equal(expectedMap.Replace("\r\n", "\n"), map.ToString());
        }
Пример #24
0
        // Use this for initialization
        private void Start()
        {
            _map.Callback += MapChanged;
            if (!isServer)
            {
                for (var i = 0; i < _map.Count; ++i)
                {
                    MapChanged(SyncList <MapCellDto> .Operation.OP_ADD, i);
                }

                InitBackgroundSize();
            }

            if (!isServer)
            {
                return;
            }

            var mapIdx  = new System.Random().Next(AvailableMaps.Length);
            var mapInfo = MapParser.Parse(AvailableMaps[mapIdx]);

            InstantiateMapObjects(mapInfo);
        }
Пример #25
0
    /* Returns maps parsed from MapParser. */
    public static List <ArenaMap> GetMaps()
    {
        MapParser mp = new MapParser();

        return(mp.Parse());
    }
Пример #26
0
 public override Parser <TInput> VisitMap <TOutput>(MapParser <TInput, TOutput> parser)
 {
     state.InputLength = parser.Parse(source, state.InputStart, output, output.Count);
     return(null);
 }
Пример #27
0
 public void Setup()
 {
     File.AppendAllLines(mapFile, wallMap);
     Map = MapParser.Parse(mapFile);
 }
Пример #28
0
        public void SimpleXmlParseTest()
        {
            var nameParser = Parsers<char>.Map(
                Parsers<char>.Some(
                    Parsers<char>.Or(new RangeParser<char>('A', 'Z'), _ => _,
                                     new RangeParser<char>('a', 'z'), _ => _)),
                list =>
                    {
                        var sb = new StringBuilder();
                        sb.Append(list.ToArray());
                        return sb.ToString();
                    });

            var valueParser = new MapParser<char, Unit, IList<char>, Unit, string>(
                    new IsParser<char>('\"'),
                    new ManyParser<char,char>( new GenericParser<char>( ch=> ch!='\"' ) ),
                    new IsParser<char>('\"'),
                    (_,value,_1) => string.Join("",value)
                );
            var attrParser = new MapParser<char, string, Unit,string, Option<Unit>, Tuple<string, string>>(
                nameParser, new IsParser<char>('='), valueParser, new OptionParser<char,Unit>( new IsParser<char>(' ') ),
                (attrName,_,attrValue,_delim)=>Tuple.Create(attrName,attrValue));

            var innerTagParser = new MapParser<char, string, Unit, IList<Tuple<string, string>>, XElement>(
                nameParser,
                new IsParser<char>(' '),
                new ManyParser<char, Tuple<string, string>>(attrParser),
                (tagName, _, attrs) =>
                    {
                        var xe = new XElement(tagName);
                        foreach (var tuple in attrs)
                        {
                            xe.Add(new XAttribute(tuple.Item1, tuple.Item2));
                        }
                        return xe;
                    }
                );

            var tagParser = new MapParser<char, Unit, XElement, Unit, XElement>(
                new IsParser<char>('<'),
                innerTagParser,
                new IsParser<char>('>'),
                (_,elm,_1) => elm
                );

            const string tagText = @"<test hoge=""hage"" foo=""bar"">";
            int endInput;
            XElement result;
            tagParser.Parse(tagText.ToList(), 0, out endInput, out result).IsTrue();
            result.Name.Is("test");
            result.Attribute("hoge").Value.Is("hage");
            result.Attribute("foo").Value.Is("bar");
        }
Пример #29
0
 public void SimpleIntegerParseTest()
 {
     var parser = new MapParser<char, char, IList<char>, string>(
             new RangeParser<char>('1','9'),
             new ManyParser<char, char>( new RangeParser<char>('0','9') ),
             (head,tail)=>
                 {
                     var sb = new StringBuilder();
                     sb.Append(head);
                     sb.Append(tail.ToArray());
                     return sb.ToString();
                 }
         );
     string result;
     int endInput;
     parser.Parse("100".ToList(), 0,out endInput, out result).IsTrue();
     result.Is("100");
     parser.Parse("1".ToList(), 0, out endInput, out result).IsTrue();
     result.Is("1");
 }
Пример #30
0
        private void Init()
        {
            var mapParser = new MapParser(this.MapPath);
            var map       = mapParser.Parse();

            this.Sounds.AddRange(map.Sounds);
            this.Models.AddRange(map.Models);

            var allShaders = ShaderParser.ReadShaders(Path.Combine(this.ETMain, "scripts")).ToList();

            var(usedTextures, usedShaderFiles) = ShaderParser.GetRequiredFiles(map, allShaders);

            this.Shaders.AddRange(usedShaderFiles);
            this.Textures.AddRange(usedTextures);

            if (MapscriptParser.HasScript(map))
            {
                var msParser  = new MapscriptParser(map);
                var mapscript = msParser.Parse();
                this.Sounds.AddRange(mapscript.Sounds);
                this.Textures.AddRange(mapscript.Remaps);
                this.MiscFiles.Add(mapscript.FullPath);
            }
            else
            {
                Log.Info($"Mapscript not found '{MapscriptParser.GetScriptPath(map.FullPath)}'");
            }

            if (SpeakerscriptParser.HasSpeakerscript(map))
            {
                var spsParser     = new SpeakerscriptParser(map);
                var speakerscript = spsParser.Parse();
                this.Sounds.AddRange(speakerscript.Sounds);
                this.MiscFiles.Add(speakerscript.FullPath);
            }
            else
            {
                Log.Info($"Speaker script not found" +
                         $" '{SpeakerscriptParser.GetScriptPath(map.FullPath)}'");
            }

            if (SoundscriptParser.HasSoundscript(map))
            {
                var ssparser    = new SoundscriptParser(map);
                var soundscript = ssparser.Parse();
                this.Sounds.AddRange(soundscript.Sounds);
                this.MiscFiles.Add(soundscript.FullPath);
            }
            else
            {
                Log.Info($"Soundscript not found" +
                         $" '{SoundscriptParser.GetScriptPath(map.FullPath)}'");
            }

            // Add lightmaps
            if (Directory.Exists(this.LightmapFolder))
            {
                var lightmaps = Directory.GetFiles(this.LightmapFolder, "lm_????.tga");

                if (!lightmaps.Any())
                {
                    Log.Warn($"Lightmap folder found but " +
                             $"contains no lightmaps ('{this.LightmapFolder}')");
                }

                this.MiscFiles.AddRange(lightmaps);
            }
            else
            {
                Log.Info($"Lightmap folder not found '{this.LightmapFolder}'");
            }

            // Add levelshots, .arena, .objdata, and tracemap
            this.GetMiscFiles();
        }
Пример #31
0
        public static void Main(string[] args)
        {
            var baseDir = args.Length > 0 ? args[0] : FindSolutionDir();

            Directory.SetCurrentDirectory(baseDir);

            var mapFiles = Directory.EnumerateFiles("Data/maps", "*.desc").ToList();
            var maps     = mapFiles.Select(
                filename =>
            {
                var mapName = Path.GetFileNameWithoutExtension(filename);
                var map     = MapParser.Parse(File.ReadAllText(filename), string.Empty);

                var originalSolution = ExtendedSolution.Load($"Data/extended-solutions/{mapName}.ext-sol");

                var boostedSolution = File.Exists($"Data/extended-solutions-packed/{mapName}.ext-sol")
                            ? ExtendedSolution.Load($"Data/extended-solutions-packed/{mapName}.ext-sol")
                            : null;

                return(new MapData
                {
                    Name = mapName,
                    OriginalSolution = originalSolution,
                    Width = map.Width,
                    Height = map.Height,
                    BoostedSolution = boostedSolution,
                });
            })
                           .ToArray();

            var nameToSolution = maps.ToDictionary(
                data => data.Name,
                data => data.OriginalSolution);

            var budget = InitialBudget;

            foreach (var map in maps.OrderBy(data => (data.GetProfit() / (float)data.BoostCost)))
            {
                if (map.BoostedSolution != null && map.BoostCost < budget)
                {
                    nameToSolution[map.Name] = map.BoostedSolution;
                    budget -= map.BoostCost;
                }
            }

            if (Directory.Exists("Data/submission"))
            {
                Directory.Delete("Data/submission", true);
            }

            Directory.CreateDirectory("Data/submission");

            foreach (var kvp in nameToSolution)
            {
                var(name, solution) = kvp;
                File.WriteAllText($"Data/submission/{name}.sol", solution.Commands);
                if (!string.IsNullOrEmpty(solution.BoosterPack))
                {
                    File.WriteAllText($"Data/submission/{name}.buy", solution.BoosterPack);
                }
            }

            var submissionFile = $"Data/submission.zip";

            if (File.Exists(submissionFile))
            {
                File.Delete(submissionFile);
            }

            ZipFile.CreateFromDirectory($"Data/submission", submissionFile);
        }
Пример #32
0
        public static void Main(string[] args)
        {
            var baseDir = args.Length > 0 ? args[0] : FindSolutionDir();

            Directory.SetCurrentDirectory(baseDir);

            var mapFiles = Directory.EnumerateFiles("Data/maps", "*.desc").ToList();
            var maps     = mapFiles.Select(
                filename =>
            {
                var mapName  = Path.GetFileNameWithoutExtension(filename);
                var map      = MapParser.Parse(File.ReadAllText(filename), string.Empty);
                var solution = ExtendedSolution.Load($"Data/extended-solutions/{mapName}.ext-sol");

                return(new MapState
                {
                    MapName = mapName,
                    OriginalTime = solution.TimeUnits ?? 0,
                    Width = map.Width,
                    Height = map.Height,
                    HasSpawns = map.NumSpawnPoints > 0,
                    NumOriginalClones = map.NumCloneBoosts,
                    NumNewClones = 0,
                });
            })
                           .ToArray();

            var budget = OriginalBudget;

            while (budget >= 2000)
            {
                budget -= 2000;

                var best       = maps[0];
                var bestProfit = 0;

                foreach (var map in maps)
                {
                    var curScore = map.ProfitWithExtra(map.NumNewClones);
                    var newScore = map.ProfitWithExtra(map.NumNewClones + 1);
                    var profit   = newScore - curScore;

                    if (profit > bestProfit)
                    {
                        best       = map;
                        bestProfit = profit;
                    }
                }

                best.NumNewClones += 1;
                best.Boosters     += 'C';
            }

            foreach (var map in maps)
            {
                if (map.NumNewClones > 0)
                {
                    Console.WriteLine($"{map.MapName} {map.Boosters}");
                }
            }
        }
Пример #33
0
        private static async Task SolveCurrentBlockAsync()
        {
            var balanceInfo = int.Parse(await FetchApiAsync("getbalance", "83"));
            var metaInfo    = JObject.Parse(await FetchApiAsync("getblockchaininfo", null));
            var blockNum    = metaInfo["block"].Value <int>();
            var blockSubs   = metaInfo["block_subs"].Value <int>();
            var blockInfo   = JObject.Parse(await FetchApiAsync("getblockinfo", blockNum.ToString()));
            var blockTs     = DateTimeOffset.FromUnixTimeSeconds((int)blockInfo["block_ts"].Value <double>());
            var blockAge    = DateTimeOffset.UtcNow - blockTs;
            var puzzleText  = blockInfo["puzzle"].Value <string>();
            var taskText    = blockInfo["task"].Value <string>();

            Console.WriteLine($"Current block: #{blockNum}, aged {blockAge}, {blockSubs} submissions, our balance: {balanceInfo}");

            var solutionDir = FindSolutionDir();
            var blockDir    = Path.Combine(solutionDir, $@"Data\blocks\{blockNum}");

            if (!Directory.Exists(blockDir))
            {
                Console.WriteLine("This is a totally new block; creating a new directory");
                Directory.CreateDirectory(blockDir);
            }

            var puzzleFile = Path.Combine(blockDir, "puzzle.cond");

            if (!File.Exists(puzzleFile))
            {
                Console.WriteLine($"Writing the original puzzle: {puzzleText}");
                File.WriteAllText(puzzleFile, puzzleText);
            }

            var puzzleSolutionFile = $"{puzzleFile}.desc";

            if (!File.Exists(puzzleSolutionFile))
            {
                Console.WriteLine("Solving puzzle");
                var seed  = 3133337;
                var tries = 0;
                while (true)
                {
                    if (++tries == 200)
                    {
                        throw new Exception("Faile to solve puzzle!");
                    }

                    Console.WriteLine($"Solving puzzle with seed {seed}");
                    var puzzle = new Puzzle(puzzleText, seed);
                    File.WriteAllText(puzzleSolutionFile, puzzle.SaveToMap());
                    puzzle.SaveToBitmap().Save($"{puzzleFile}.png");
                    try
                    {
                        puzzle.EnsureMapIsValid(puzzleSolutionFile);
                        Console.WriteLine("Have a valid solution");
                        break;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Puzzle solution is invalid: {ex.Message}");
                        ++seed;
                    }
                }
            }

            var taskFile = Path.Combine(blockDir, "task.desc");

            if (!File.Exists(taskFile))
            {
                Console.WriteLine($"Writing the original task: {taskText}");
                File.WriteAllText(taskFile, taskText);
            }

            var extSolutionFile = $"{taskFile}.ext-sol";
            var solutionFile    = $"{taskFile}.sol";

            Console.WriteLine("Solving task");
            var sw = new Stopwatch();

            sw.Start();

            // shuffled strategies list
            var strategies = StrategyFactory.GenerateStrategies().ToArray();
            var rng        = new Random();

            strategies = new[] { new DumbBfs() }.Concat(strategies.OrderBy(s => rng.Next())).ToArray();

            // Block lives for 15 minutes, lets try to solve everything by 14:00
            var blockLifetimeMs = 10 * 60 * 1000;
            var timeToSolve     = Math.Max(5000, blockLifetimeMs - blockAge.TotalMilliseconds);

            Console.WriteLine($"Time to solve: {timeToSolve} ms");

            var map       = MapParser.Parse(taskText, string.Empty);
            var solutions = strategies.AsParallel().WithDegreeOfParallelism(10)
                            .Select(
                strategy =>
            {
                var run = false;
                lock (sw)
                {
                    run = sw.ElapsedMilliseconds < timeToSolve;
                }

                return(run
                            ? Emulator.MakeExtendedSolution(map, strategy, string.Empty)
                            : Emulator.MakeExtendedSolution(map, "fail", new Command[][] { }, string.Empty));
            });

            var numSuccess = 0;

            foreach (var sln in solutions)
            {
                if (sln.IsSuccessful)
                {
                    ++numSuccess;
                }

                sln.SaveIfBetter(extSolutionFile);
            }

            Console.WriteLine($" Solution took: {sw.ElapsedMilliseconds} ms, {numSuccess} strategies out of {strategies.Length} successed");

            var extSolution = ExtendedSolution.Load(extSolutionFile);

            if (!extSolution.IsSuccessful)
            {
                throw new Exception("ext solution is not successful!");
            }

            File.WriteAllText(solutionFile, extSolution.Commands);

            var submissionResultFile = Path.Combine(blockDir, "submit.txt");

            if (!File.Exists(submissionResultFile))
            {
                Console.WriteLine("SUBMITTING!");

                var payload = new MultipartFormDataContent();
                payload.Add(new StringContent("2a78df7b478788ae4cf9d338"), "private_id");
                payload.Add(new StringContent(blockNum.ToString()), "block_num");
                payload.Add(new ByteArrayContent(File.ReadAllBytes(solutionFile)), "solution", "task.desc.sol");
                payload.Add(new ByteArrayContent(File.ReadAllBytes(puzzleSolutionFile)), "puzzle", "puzzle.cond.desc");

                var httpClient = new HttpClient();
                var response   = await httpClient.PostAsync($"{BlockChainUrl}/submit", payload);

                var submissionResult = await response.Content.ReadAsStringAsync();

                Console.WriteLine($"RESULT: {submissionResult}");
                File.WriteAllText(submissionResultFile, submissionResult);
            }
        }