Example #1
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");
 }
Example #2
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!");
        }
Example #3
0
        public frmEditLocation(Location Loc, MapParser MapParser, LocationParser LocParser, bool NewLoc)
        {
            this.NewLoc    = NewLoc;
            this.MapParser = MapParser;
            this.LocParser = LocParser;
            this.Loc       = Loc;
            if (Loc != null)
            {
                LoadedPid = Loc.Pid;
            }
            InitializeComponent();

            toolTip = new ToolTip();
            toolTip.SetToolTip(lblName, "Internal name, used to generate define (for _maps.fos)");
            toolTip.SetToolTip(lblWmName, "Worldmap name, shown in-game on the worldmap.");
        }
Example #4
0
 //********************** START GAME ********************
 void InitNewGame()
 {
     CameraScript.ResetZoom();
     nextGameTimer.Reset();
     //spawn map with already intantiated gameObjects
     levelMap = MapParser.GetRandomMap();
     ExtractSpecificFromAllGO();
     //set camera position
     SetCameraPosition();
     //*************************************** SPAWN BACKGROUND OBJECT ******************************************
     DestroyBackground();
     backgroundObject = (GameObject)MonoBehaviour.Instantiate(Resources.Load <GameObject>(FilePaths.objBackgroundBack), new Vector3(CameraScript.camPos.x, CameraScript.camPos.y, 10), Quaternion.identity);
     //chose where characters will spawn
     InitCharacters();
     SetCharactersPosition();
 }
Example #5
0
        private void btnReadMap_Click(object sender, EventArgs e)
        {
            MapParser parser    = new MapParser();
            string    sizeValue = parser.GetMapSize(tbFilename.Text.Trim());

            tbCurrentSize.Text = "";
            if (!String.IsNullOrEmpty(sizeValue))
            {
                if (sizeValue.Contains("|"))
                {
                    int      width  = -1;
                    int      height = -1;
                    int      wNew   = -1;
                    int      hNew   = -1;
                    string[] parts  = sizeValue.Split('|');
                    if (parts.Length >= 2 && parts[0] != null && parts[1] != null)
                    {
                        int.TryParse(parts[0], out width);
                        int.TryParse(parts[1], out height);
                    }
                    sizeValue  = "Filename: " + Path.GetFileName(tbFilename.Text) + "\r\n";
                    sizeValue += "Current size: " + width + "x" + height + "\r\n";
                    wNew       = width + (int)numLeft.Value + (int)numRight.Value;
                    hNew       = height + (int)numTop.Value + (int)numBottom.Value;
                    sizeValue += "Expected new size: " + wNew + "x" + hNew + "\r\n";
                    if (wNew > 511 || hNew > 511)
                    {
                        sizeValue += "Max size limit of W or H is 511\r\n";
                    }
                    else if (wNew + hNew > 512)
                    {
                        sizeValue += "Max size game limit W+H=512\r\n";
                    }
                    if (wNew < 0 || hNew < 0)
                    {
                        sizeValue += "Map size in negative\r\n";
                    }
                    else if ((wNew * 2 - 1) * hNew < 780)
                    {
                        sizeValue += "Map size too small\r\n";
                    }
                }
                tbCurrentSize.Text += sizeValue;
            }
        }
        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);
        }
Example #7
0
    public BrickList ParseClipboard()
    {
        BrickList returnList = new BrickList();
        string    text       = Helper.ReadClipboard();

        if (text.StartsWith("{\"bricks\":"))   // brickbuilder json clipboard format
        {
            returnList = JsonUtility.FromJson <BrickList>(text);
        }
        else
        {
            try {
                returnList = MapParser.ParseBRKBricks(text);
            } catch (Exception e) {
                Debug.LogException(e);
            }
        }
        return(returnList);
    }
        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);
            }
        }
Example #9
0
        public void MapParser_CreateMap_MapCreatedCorrectly()
        {
            var test = @"
######
#PWM #
######";
            var map  = MapParser.GetMapFromText(test);

            map.GetLength(0).Should().Be(6);
            map.GetLength(1).Should().Be(3);
            map[0, 0].Length.Should().Be(1);
            map[0, 0].Should().ContainItemsAssignableTo <UnbreakableWall>();
            map[1, 1].Length.Should().Be(1);
            map[1, 1].Should().ContainItemsAssignableTo <Player>();
            map[2, 1].Length.Should().Be(1);
            map[2, 1].Should().ContainItemsAssignableTo <BreakableWall>();
            map[3, 1].Length.Should().Be(1);
            map[3, 1].Should().ContainItemsAssignableTo <PredictableRobot>();
            map[4, 1].Should().BeEmpty();
        }
Example #10
0
        private void LoadMapFiles()
        {
            Log.Info("Loading map data please wait...");
            foreach (var mapId in this.Conf.Maps)
            {
                var map       = new Map(mapId);
                var mapParser = new MapParser(this.Conf.GetMapFilePath(mapId));
                mapParser.ParseFile(ref map);
                var ndtParser = new NdtParser(this.Conf.GetNdtFilePath(mapId));
                ndtParser.ParseFile(ref map);
                foreach (var shop in map.Shops)
                {
                    if (this.GameData.NPCData.ContainsKey(shop.Id))
                    {
                        continue;
                    }

                    var npcData       = new NPCData();
                    var npcDataParser = new NPCDataParser(this.Conf.GetNpcFilePath(shop.Id));
                    npcDataParser.ParseData(ref npcData);
                    this.GameData.NPCData.Add(shop.Id, npcData);
                }

                foreach (var monster in map.Monsters)
                {
                    if (this.GameData.NPCData.ContainsKey(monster.Id))
                    {
                        continue;
                    }

                    var npcData       = new NPCData();
                    var npcDataParser = new NPCDataParser(this.Conf.GetNpcFilePath(monster.Id));
                    npcDataParser.ParseData(ref npcData);
                    this.GameData.NPCData.Add(monster.Id, npcData);
                }

                this.GameData.Maps.Add(mapId, map);
            }

            Log.Info("Loaded " + this.GameData.Maps.Count + " maps");
        }
Example #11
0
        public static GameObject LoadMap(string path, string pathToTextures, Shader diffuse = null, Shader transparent = null,
                                         bool generateCollisionMesh = true)
        {
            if (Mathf.Approximately(MapScaleFactor, 0))
            {
                Debug.LogError("MapScaleFactor cannot be 0!");
                return(null);
            }

            _materialCache.Clear();
            _wadsUsed.Clear();

            _pathToMapTextures     = pathToTextures;
            _diffuseShader         = diffuse;
            _transparentShader     = transparent;
            _generateCollisionMesh = generateCollisionMesh;

            MapFile map = MapParser.ParseMap(path);

            return(BuildMapMesh(map));
        }
Example #12
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));
        }
Example #13
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);
     }
 }
Example #14
0
 //top GUI listeners
 void SaveButtonListener()
 {
     saveButton.onClick.AddListener(
         delegate {
         string inputText = mapNameInput.text.ToString();
         if (inputText == "" || inputText == null)
         {
             inputText = mapChoiceDropdown.value.ToString();
         }
         //get maps from json, remove duplicates,save new map, save to json
         List <LevelMap> allMaps = MapParser.GetAllLevelMapsFromJSON();
         LevelMap.RemoveCopiesWithSameName(inputText, ref allMaps);
         mapEditor.map.name = inputText;
         allMaps.Add(mapEditor.map);
         MapParser.SaveLevelMapsToJSON(allMaps);
         //destroy allMaps except active one because they dont need to be on screen(bad solution but works)
         LevelMap.ClearAllMaps(ref allMaps);
         //refresh dropdown to display saved map
         InitMapChoiceItems();
     });
 }
Example #15
0
    public LevelRoadRacer(MainGame tempGame)
    {
        _game    = tempGame;
        FileName = @"RoadRacerLevel/RoadRacer.tmx";
        Map _levelData = MapParser.ReadMap(FileName);

        SpawnRoad(_levelData);

        _obst = new Obstacles(tempGame);
        _obst.SetXY(game.width / 2, 0);
        AddChild(_obst);

        _overlay = new Overlay();
        AddChild(_overlay);
        _player = new PlayerRoadRacer(this, tempGame);
        AddChild(_player);

        Sound backgroundMusic = new Sound("Sounds/RoadRacerSong.mp3", true, true);

        _backgroundMusicChannel        = backgroundMusic.Play();
        _backgroundMusicChannel.Volume = 1f;
    }
Example #16
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());
        }
Example #17
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);
        }
Example #18
0
        public Level MakeLevel()
        {
            Stream    boardStream = null;
            MapParser parser      = GetMapParser();

            try
            {
                System.Reflection.Assembly myAssembly = System.Reflection.Assembly.GetExecutingAssembly();
                boardStream = myAssembly.GetManifestResourceStream("CsPacman.board.txt");
                return(parser.ParseMap(boardStream));
            }
            catch (IOException e)
            {
                throw new PacmanConfigurationException("Unable to create level.", e);
            }
            finally
            {
                if (boardStream != null)
                {
                    boardStream.Dispose();
                }
            }
        }
Example #19
0
        private void WriteHeights(string file, int w, int h)
        {
            byte[] hd = new byte[w * h * 17 + 8];
            int    i  = 0;

            BitConverter.GetBytes(w).CopyTo(hd, i); i += 4;
            BitConverter.GetBytes(h).CopyTo(hd, i); i += 4;
            Vector3I loc = Vector3I.Zero;
            LEVGR    vgr = new LEVGR();

            for (loc.Z = 0; loc.Z < h; loc.Z++)
            {
                for (loc.X = 0; loc.X < w; loc.X++)
                {
                    ColumnResult cr = MapParser.GetColumn(state.World, loc.X, loc.Z, w, h, vgr);
                    BitConverter.GetBytes(cr.Height.XNZN).CopyTo(hd, i); i += 4;
                    BitConverter.GetBytes(cr.Height.XPZN).CopyTo(hd, i); i += 4;
                    BitConverter.GetBytes(cr.Height.XNZP).CopyTo(hd, i); i += 4;
                    BitConverter.GetBytes(cr.Height.XPZP).CopyTo(hd, i); i += 4;
                    hd[i++] = cr.Walls;
                }
            }

            using (MemoryStream ms = new MemoryStream()) {
                var gs = new GZipStream(ms, CompressionMode.Compress, true);
                gs.Write(hd, 0, hd.Length);
                gs.Close();
                ms.Position = 0;
                using (var s = File.Create(file)) {
                    var bw = new BinaryWriter(s);
                    bw.Write(hd.Length);
                    bw.Flush();
                    ms.CopyTo(s);
                    s.Flush();
                }
            }
        }
Example #20
0
    void OnGUI()
    {
        //GUI.skin = Skin;

        if (GUI.Button(new Rect(5, 5, 160, 35), "Load map"))
        {
            string[] path = StandaloneFileBrowser.OpenFilePanel("Open trk file", CrashdayPath + "/user/", "trk", false);
            if (path.Length != 0 && path[0].Length != 0)
            {
                PlayerPrefs.SetString("lastmappath", path[0]);
                Track = MapParser.ReadMap(path[0]);
                GetComponent <TrackManager>().LoadTrack(Track);
            }
        }

        if (GUI.Button(new Rect(175, 5, 160, 35), "Save map"))
        {
            string path = StandaloneFileBrowser.SaveFilePanel("Save trk file", CrashdayPath + "/user/", "my_awesome_track", "trk");
            if (path.Length != 0)
            {
                MapParser.SaveMap(GetComponent <TrackManager>().CurrentTrack, path);
            }
        }
    }
Example #21
0
 public override Parser <TInput> VisitMap <TOutput>(MapParser <TInput, TOutput> parser)
 {
     state.InputLength = parser.Parse(source, state.InputStart, output, output.Count);
     return(null);
 }
 public override void VisitMap <TOutput>(MapParser <TInput, TOutput> parser)
 {
     WriteTerm("map()");
 }
Example #23
0
 public frmAddMaps(MapParser MapParser, List <Map> UsedMaps)
 {
     this.UsedMaps  = UsedMaps;
     this.MapParser = MapParser;
     InitializeComponent();
 }
Example #24
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();
        }
Example #25
0
 private HexaModel[][] GetMap(bool newMap)
 {
     if(parser == null || newMap)
       parser = new MapParser();
     GameSettings gs = GameMaster.Inst().GetGameSettings();
     if (GameMaster.Inst().GetMapSource() == null)
         return parser.getMap(gs.GetMapSizeXML(), gs.GetMapTypeXML(), gs.GetMapWealthXML());
     else
         return parser.parseCampaignMap(GameMaster.Inst().GetMapSource());
 }
Example #26
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");
 }
 public TiledMapLoader(MapParser mapParser)
 {
     parser = mapParser;
 }
Example #28
0
 public TiledMapLoader(MapParser mapParser)
 {
     parser = mapParser;
 }
        /// <summary>
        /// Get all farm from travianstats.de
        /// </summary>
        /// <returns></returns>
        public async static Task <List <InactiveFarm> > GetFarms(Account acc, Coordinates Coords, int Distance)
        {
            var serverUrl = acc.AccInfo.ServerUrl;
            // get serverUrl without https://
            var url = (new UriBuilder(serverUrl)).Host;

            if (!(await CheckServerSupport(acc, url)))
            {
                return(null);
            }

            var Client = acc.Wb.RestClient;

            var moreFarm = true;
            var index    = 1;
            var result   = new List <InactiveFarm>();

            while (moreFarm)
            {
                Client.BaseUrl = new Uri($"https://www.inactivesearch.it/inactives/{url}?c={Coords.x}|{Coords.y}&page={index}");
                var request  = new RestRequest(Method.GET);
                var response = await Client.ExecuteAsync(request);

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return(null);
                }

                var doc = new HtmlAgilityPack.HtmlDocument();
                doc.LoadHtml(response.Content);

                // table
                var table = doc.DocumentNode.SelectNodes("//table[@class='table table-condensed table-inactives table-shadow']//tbody") // they use myTable for naming their table ?_?
                            .Descendants("tr")
                            .Where(tr => tr.Elements("td").Count() > 1)
                            .Select(tr => tr.Elements("td").Select(td => td.InnerText.Trim().Replace("\t", "").Replace("\n", "")).ToList())
                            .ToList();

                if (table.Count < 1)
                {
                    moreFarm = false;
                    break;
                }

                foreach (var row in table)
                {
                    try
                    {
                        var intDistance = int.Parse(row[0].Split('.').First());
                        if (intDistance > Distance)
                        {
                            moreFarm = false;
                            break;
                        }
                        result.Add(new InactiveFarm()
                        {
                            distance = intDistance,
                            coord    = MapParser.GetCoordinates(row[1]),
                            nameVill = row[2],
                            // row[3] hide village button
                            // row[4] attack button
                            population = int.Parse(row[5].Split('+').First().Split('-').First()),
                            // row[6], [7], [8], [9] population previous day
                            // row[10] icon tribe
                            namePlayer = row[11],
                            nameAlly   = row[12],
                        });
                    }
                    catch (Exception) { }
                }

                index++;
            }

            return(result);
        }
Example #30
0
        /// <summary>
        /// Get all farm from travianstats.de
        /// </summary>
        /// <param name="serverCode"></param>
        /// <returns></returns>
        public async static Task <List <InactiveFarm> > GetFarms(Account acc, Coordinates Coords, int Distance)
        {
            var ServerCode = await GetServerCode(acc);

            if (string.IsNullOrEmpty(ServerCode))
            {
                return(null);
            }

            var Client = acc.Wb.RestClient;

            Client.BaseUrl = new Uri("https://travianstats.de");
            var request = new RestRequest($"?m=inactive_finder&w={ServerCode}", Method.POST);

            request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
            request.AddHeader("Cookie", $"tcn_world={ServerCode}");
            request.AddParameter("m", "inactivefinder");
            request.AddParameter("w", ServerCode);
            request.AddParameter("x", $"{Coords.x}");
            request.AddParameter("y", $"{Coords.y}");
            request.AddParameter("distance", $"{Distance}");

            var response = await Client.ExecuteAsync(request);

            if (response.StatusCode != HttpStatusCode.OK)
            {
                return(null);
            }

            if (response.Content.Contains("Nothing found"))
            {
                return(null);
            }

            var doc = new HtmlAgilityPack.HtmlDocument();

            doc.LoadHtml(response.Content);

            // table
            var table = doc.DocumentNode.SelectNodes("//table[@id='myTable']//tbody") // they use myTable for naming their table ?_?
                        .Descendants("tr")
                        .Where(tr => tr.Elements("td").Count() > 1)
                        .Select(tr => tr.Elements("td").Select(td => td.InnerText.Trim().Replace("\t", "").Replace("\n", "")).ToList())
                        .ToList();

            var result = new List <InactiveFarm>();

            foreach (var row in table)
            {
                try
                {
                    result.Add(new InactiveFarm()
                    {
                        //status = row[0]
                        distance   = int.Parse(row[1]),
                        coord      = MapParser.GetCoordinates(row[2]),
                        namePlayer = row[3],
                        nameAlly   = row[4],
                        nameVill   = row[5],
                        population = int.Parse(row[6])
                                     //functions = row[7]
                    });
                }
                catch (Exception) { }
            }

            return(result);
        }
Example #31
0
 public MapGenerator()
 {
     _parser = new MapParser();
 }
 // Run this program to push new design elements into
 // their abstract representations within the game
 // solution.
 static void Main()
 {
     // Run the map parser.
     MapParser parser = new MapParser();
 }
Example #33
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");
        }
Example #34
0
        private static void Main()
        {
            ConsoleSettings.PrepareConsole();
            KeyboardInterface keyboard = new KeyboardInterface();

            Opponent enemy = new Opponent(new MatrixCoords(3, 3), new char[, ] {
                { '@' }
            }, null);

            ConsoleRenderer renderer = new ConsoleRenderer(ConsoleSettings.ConsoleHeight, ConsoleSettings.ConsoleWidth);

            IList <WorldObject> map = MapParser.ParseMap("../../WorldMaps/map.txt");

            GameEngine.GameEngine gameEngine = new GameEngine.GameEngine(renderer, keyboard);

            int heroChosen = 0;

            Console.WriteLine("Please select your Hero: \nPress 1 for  Mage\nPress 2 for  Thief\nPress 3 for  Warrior");

            // validates hero choice and let's player choose correctly
            do
            {
                try
                {
                    heroChosen = int.Parse(Console.ReadLine());
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine("Please choose 1, 2 or 3");
                }
            } while (!true || heroChosen < 1 || heroChosen > 3);

            Console.Clear();

            // TODO implement interface for the choice of type of character
            MainCharacter hero = HeroChoice(heroChosen);

            hero.AddWeapon(new Knife("Steel knife")
            {
                MinDmg = 20, MaxDmg = 30
            });
            //hero.AddWeapon(new Knife("mnogo qk knife") { MaxDmg = 30, MinDmg = 20 });
            gameEngine.AddObject(hero);
            gameEngine.AddObject(enemy);
            Opponent newOpponent = new Opponent(new MatrixCoords(2, 35), new char[, ] {
                { '@' }
            }, new BattleAxe("Battle Axe"));
            Opponent newOpponent2 = new Opponent(new MatrixCoords(7, 30), new char[, ] {
                { '@' }
            }, new Knife("Steel knife"));
            Opponent newOpponent3 = new Opponent(new MatrixCoords(10, 10), new char[, ] {
                { '@' }
            }, new BattleAxe("Battle Axe"));
            Opponent newOpponent4 = new Opponent(new MatrixCoords(15, 15), new char[, ] {
                { '@' }
            }, new BattleAxe("Battle Axe"));

            gameEngine.AddObject(newOpponent);
            gameEngine.AddObject(newOpponent2);
            gameEngine.AddObject(newOpponent3);
            gameEngine.AddObject(newOpponent4);
            foreach (var item in map)
            {
                gameEngine.AddObject(item);
            }

            keyboard.OnDownPressed   += (sender, eventInfo) => { hero.Move(Direction.Down); };
            keyboard.OnLeftPressed   += (sender, eventInfo) => { hero.Move(Direction.Left); };
            keyboard.OnRightPressed  += (sender, eventInfo) => { hero.Move(Direction.Right); };
            keyboard.OnUpPressed     += (sender, eventInfo) => { hero.Move(Direction.Top); };
            keyboard.onPotionPressed += (sencer, eventInfo) => { hero.Health += 5; };

            gameEngine.Run();
        }
Example #35
0
 public MapParserTests()
 {
     factory          = new LexerFactory(null, lexerLogger.Object);
     expressionParser = new MappedDataExpressionParser();
     parser           = new MapParser(factory, expressionParser, exampleLoader.Object, logger.Object);
 }