Exemplo n.º 1
0
		/// <summary>
		/// Default constructor.
		/// </summary>
		/// <param name="engine">The rewriting engine.</param>
		/// <param name="rawUrl">The initial, raw URL.</param>
		/// <param name="httpMethod">The HTTP method used (GET, POST, ...)</param>
		/// <param name="mapPath">The method to use for mapping paths.</param>
		/// <param name="serverVariables">Collection of server variables.</param>
		/// <param name="headers">Collection of headers.</param>
		/// <param name="cookies">Collection of cookies.</param>
		internal RewriteContext(RewriterEngine engine,
			string rawUrl, string httpMethod,
			MapPath mapPath,
			NameValueCollection serverVariables,
			NameValueCollection headers,
			HttpCookieCollection cookies)
		{
			_engine = engine;
			_location = rawUrl;
			_method = httpMethod;
			_mapPath = mapPath;

			foreach (string key in serverVariables)
			{
				_properties.Add(key, serverVariables[key]);
			}

			foreach (string key in headers)
			{
				_properties.Add(key, headers[key]);
			}

			foreach (string key in cookies)
			{
				_properties.Add(key, cookies[key].Value);
			}
		}
Exemplo n.º 2
0
        private void _map_OnRightClick(object sender, MapPointLatLon pos)
        {
            Waypoint click = new Waypoint(new OsmNode(1, pos.Lat, pos.Lon));

            Waypoint nearest = _streets.Waypoints.Values.OrderBy(w => w.DistanceTo(click)).First();

            if (_clickIndex == 0)
            {
                if (_currentPath != null)
                {
                    _map.RemovePath(_currentPath);
                    _currentPath = null;
                }

                _startPoint = nearest;
                _endPoint   = null;

                _clickIndex = 1;
            }
            else if (_clickIndex == 1)
            {
                _endPoint = nearest;

                var p = _streets.FindPath(_startPoint, _endPoint);
                if (p != null)
                {
                    _currentPath = _map.AddPath(_routeLayer, p.Waypoints.Select(wp => new MapPointLatLon(wp.Lat, wp.Lon)), Color.Red);
                }

                _clickIndex = 0;
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="engine">The rewriting engine.</param>
        /// <param name="rawUrl">The initial, raw URL.</param>
        /// <param name="httpMethod">The HTTP method used (GET, POST, ...)</param>
        /// <param name="mapPath">The method to use for mapping paths.</param>
        /// <param name="serverVariables">Collection of server variables.</param>
        /// <param name="headers">Collection of headers.</param>
        /// <param name="cookies">Collection of cookies.</param>
        internal RewriteContext(RewriterEngine engine,
                                string rawUrl, string httpMethod,
                                MapPath mapPath,
                                NameValueCollection serverVariables,
                                NameValueCollection headers,
                                HttpCookieCollection cookies)
        {
            _engine   = engine;
            _location = rawUrl;
            _method   = httpMethod;
            _mapPath  = mapPath;

            foreach (string key in serverVariables)
            {
                _properties.Add(key, serverVariables[key]);
            }

            foreach (string key in headers)
            {
                _properties.Add(key, headers[key]);
            }

            foreach (string key in cookies)
            {
                _properties.Add(key, cookies[key].Value);
            }
        }
Exemplo n.º 4
0
        private void DrawPath(MapPath path, bool close = false)
        {
            if (path.Points.Count < 2)
            {
                return;
            }

            Color      c        = _pathColors[path];
            MapVectorD lastView = _map.LatLonToViewPoint(path.Points[0]);

            for (int i = 1; i < path.Points.Count; i++)
            {
                var currentView = _map.LatLonToViewPoint(path.Points[i]);

                if (_map.ViewBounds.Contains(currentView) || _map.ViewBounds.Contains(lastView))
                {
                    _sBatch.DrawLine(lastView.ToVector2(), currentView.ToVector2(), c, (float)path.LineWidth);
                }

                lastView = currentView;
            }

            if (close)
            {
                var firstView = _map.LatLonToViewPoint(path.Points[0]);
                if (_map.ViewBounds.Contains(firstView) || _map.ViewBounds.Contains(lastView))
                {
                    _sBatch.DrawLine(lastView.ToVector2(), firstView.ToVector2(), c, (float)path.LineWidth);
                }
            }
        }
Exemplo n.º 5
0
    public void FromJson(Hashtable json)
    {
        ArrayList nodes = json["Nodes"] as ArrayList;

        foreach (Hashtable nodeHash in nodes)
        {
            XY      coord = new XY(nodeHash["Coord"] as Hashtable);
            MapRoom room  = new MapRoom(nodeHash["Room"] as Hashtable);

            Graph.AddNode(coord, room);
        }

        ArrayList edges = json["Edges"] as ArrayList;

        foreach (Hashtable edgeHash in edges)
        {
            MapNode from = Graph.GetNodeByCoord(new XY(edgeHash["From"] as Hashtable));
            MapNode to   = Graph.GetNodeByCoord(new XY(edgeHash["To"] as Hashtable));
            MapPath path = new MapPath(edgeHash["Path"] as Hashtable);

            Graph.AddEdge(from, to, path);
        }

        Entrance = Graph.GetNodeByCoord(new XY(json["Entrance"] as Hashtable));
    }
Exemplo n.º 6
0
    public static MapPath CreateJoggingPath(Vector2 start, Vector2 end, float jogWidthMin, float jogWidthMax, float pathLengthMin, float pathLengthMax, float pathWidthMin, float pathWidthMax)
    {
        MapPath path = new MapPath(start);
        //float minX = Map.StaticMap.MapOrigin.x;
        //float maxX = Map.StaticMap.MapOrigin.x + Map.StaticMap.MapWidth;
        //float minY = Map.StaticMap.MapOrigin.y;
        //float maxY = Map.StaticMap.MapOrigin.y + Map.StaticMap.MapHeight;

        Vector2 direction = (end - start).normalized;                    //vector direction towards end point
        Vector2 normal    = Vector2.Perpendicular(direction).normalized; //normal vector to direction vector for jogging path
        Vector2 current   = start;                                       //current jog point
        Vector2 linePoint = start;                                       //closest point on line to current jog point

        while (path.Count < 1 || path.Points[path.Count - 1] != end)
        {
            Vector2 forward = Random.Range(pathLengthMin, pathWidthMax) * direction;
            Vector2 jog     = Random.Range(jogWidthMin, jogWidthMax) * normal;
            float   width   = Random.Range(pathWidthMin, pathWidthMax);
            float   nextX   = forward.x + jog.x + linePoint.x;
            float   nextY   = forward.y + jog.y + linePoint.y;
            linePoint = Utility.ClosestPointOnLine(new Vector2(nextX, nextY), start, end);
            if (Vector2.Distance(current, end) < pathLengthMin || linePoint == end)
            {
                nextX = end.x;
                nextY = end.y;
            }
            current = new Vector2(nextX, nextY);
            path.Add(current, width);
        }
        return(path);
    }
Exemplo n.º 7
0
        internal void MoveTo(string dest)
        {
            buttonNavigator.Checked      = true;
            AppVars.AutoMoving           = true;
            AppVars.AutoMovingDestinaton = dest;
            var path = new MapPath(AppVars.Profile.MapLocation, new[] { dest });

            if (path.IsIslandRequired)
            {
                AppVars.MainForm.FastStartSafe("Телепорт (Остров Туротор)", AppVars.Profile.UserNick);
            }

            AppVars.AutoMovingMapPath = path;

            UpdateFishOff();
            try
            {
                if (AppVars.MainForm != null)
                {
                    AppVars.MainForm.BeginInvoke(
                        new ReloadMainPhpInvokeDelegate(AppVars.MainForm.ReloadMainPhpInvoke),
                        new object[] { });
                }
            }
            catch (InvalidOperationException)
            {
            }
        }
Exemplo n.º 8
0
    public void Goto(MapPath location)
    {
        Reset();
        var mapPair = SpawnMapPair(location.mapName, Vector3.zero, Vector2.zero);

        if (player != null)
        {
            var map = isDead ? mapPair.deadMap : mapPair.livingMap;

            var staringPoints = map.GetComponentsInChildren <StartingPoint>();

            StartingPoint start = null;

            foreach (var check in staringPoints)
            {
                if (check.locationName == location.portalName)
                {
                    start = check;
                    break;
                }
            }

            player.transform.position = start == null?LerpMap(map, new Vector2(0.5f, 0.5f)) : start.transform.position;
        }
    }
Exemplo n.º 9
0
        public void pathfinding()
        {
            GameObject    gameObject    = new GameObject();
            MapGeneration mapGeneration = gameObject.AddComponent <MapGeneration>();

            mapGeneration.HexagonPrefab = new GameObject();
            mapGeneration.MapRadius     = 10;

            mapGeneration.HexDict = new Dictionary <Vector3Int, IHexagon>();
            mapGeneration.GenerateMap();
            mapGeneration.UpdateHexNeighbours();
            mapGeneration.ConnectContentsToHex();

            IHexagon start_hex = mapGeneration.HexDict[new Vector3Int(0, 0, 0)];
            IHexagon end_hex   = mapGeneration.HexDict[new Vector3Int(0, -4, 4)];

            MapPathfinding mapPathfinding = new MapPathfinding();
            MapPath        path           = mapPathfinding.GeneratePath(start_hex, end_hex);

            MapPath arbitrary_path = new MapPath();

            for (int i = 4; i >= 0; i--)
            {
                arbitrary_path.PathStack.Push(mapGeneration.HexDict[new Vector3Int(0, -i, i)]);
            }
            arbitrary_path.cost = 4;

            Assert.AreEqual(arbitrary_path.PathStack, path.PathStack);
            Assert.AreEqual(arbitrary_path.cost, path.cost);
        }
Exemplo n.º 10
0
    /// <summary>
    /// 选择路径最短的目标
    /// </summary>
    protected int GetShortTarget(MapGrid Pos)
    {
        if (mTargetlist.Count == 0)
        {
            return(-1);
        }
        if (mTargetlist.Count == 1)
        {
            return(mTargetlist[0].SceneID);
        }

        List <MapGrid> list = new List <MapGrid> ();

        for (int i = 0; i < mTargetlist.Count; i++)
        {
            MapGrid m = mTargetlist[i].GetMapGrid();
            if (m == null)
            {
                Debug.Log("lifeM 获取格子为NULL 请调查");
                continue;
            }
            list.Add(m);
        }

        int Shortest = MapPath.FindShortestTarget(list, Pos);

        if (Shortest >= 0)
        {
            return(mTargetlist[Shortest].SceneID);
        }
        return(-1);
    }
Exemplo n.º 11
0
 public void PointToDest(IList <string> dest)
 {
     try
     {
         var start = AppVars.Profile.MapLocation;
         var path  = new MapPath(start, dest);
         if (path.PathExists)
         {
             Text               = $"Маршрут до {path.Destination}";
             textDest.Text      = path.Destination;
             _destination       = path.Destination;
             labelJumps.Text    = path.Jumps.ToString();
             labelBotLevel.Text = path.BotLevel.ToString();
             labelTied.Text     = $"~{AppVars.Tied + (path.Jumps*2)}%";
             UpdateMap(_destination);
             buttonOk.Enabled = true;
         }
         else
         {
             Text               = @"Навигатор";
             labelJumps.Text    = @"-";
             labelBotLevel.Text = @"-";
             labelTied.Text     = @"-";
             UpdateMap(AppVars.Profile.MapLocation);
             buttonOk.Enabled = false;
         }
     }
     catch (NullReferenceException)
     {
     }
 }
Exemplo n.º 12
0
    /*
     * private static List<MapGrid> ProcessNeighbour(MapGrid node,MapGrid endN)
     * {
     *      Vector3 pos = endN.pos;
     *      List<MapGrid> l = new List<MapGrid>();
     *      List<float> lcost = new List<float>();
     *      for(int nNSDir=(int)NearestStationDir.NSD_LEFTTOP; nNSDir<(int)NearestStationDir.NSD_END;nNSDir++)
     *      {
     *              if(node.m_NpNearestStation[nNSDir]!=null)
     *              {
     *                      l.Add(node.m_NpNearestStation[nNSDir]);
     *                      lcost.Add(node.m_NfNearestStationscoreG[nNSDir]);
     *              }
     *      }
     *      if (node.pNearestSpecialStation !=null)
     *      {
     *              l.Add(node.pNearestSpecialStation);
     *              lcost.Add(node.fNearestSpecialscoreG);
     *      }
     *
     *      for(int i=0; i<l.Count; i++){
     *              //Debug.Log(neighbourNode[i].listState);
     *              //if the neightbour state is clean (never evaluated so far in the search)
     *              if(l[i].listState==MapGrid._ListState.Unassigned){
     *                      //check the score of G and H and update F, also assign the parent to currentNode
     *                      l[i].scoreG=node.scoreG+lcost[i];
     *                      l[i].scoreH=Vector3.Distance(l[i].pos, pos);
     *                      l[i].scoreF = l[i].scoreG + l[i].scoreH;
     *                      l[i].preNode=node;
     *              }
     *              //if the neighbour state is open (it has been evaluated and added to the open list)
     *              else if(l[i].listState==MapGrid._ListState.Open){
     *                      //calculate if the path if using this neighbour node through current node would be shorter compare to previous assigned parent node
     *                      float tempScoreG=node.scoreG+lcost[i];
     *                      if(l[i].scoreG>tempScoreG){
     *                              //if so, update the corresponding score and and reassigned parent
     *                              l[i].preNode=node;
     *                              l[i].scoreG=tempScoreG;
     *                              l[i].scoreF = l[i].scoreG + l[i].scoreH;
     *                      }
     *              }
     *      }
     *      return l;
     * }
     */
    //分支 end
    public static int FindShortestTarget(List <MapGrid> t, MapGrid start)
    {
        if (t == null || t.Count == 0 || start == null)
        {
            return(-1);
        }
        int nTargetCount = t.Count;

        if (nTargetCount == 1)
        {
            return(0);
        }

        int   iTarget    = -1;
        float fScoreGMax = 1000000;

        //最短路径查找方法。
        for (int i = 0; i < nTargetCount; i++)
        {
            if (t[i] == null)
            {
                continue;
            }
            float fScore = MapPath.GetPathScoreG(start, t[i]);
            if (fScore < 0 || fScore >= fScoreGMax)
            {
                continue;
            }
            fScoreGMax = fScore;
            iTarget    = i;
        }
        return(iTarget);
    }
        void GenerateItems()
        {
            ActiveItem = null;
            SolvedItems.Clear();
            this.isLoading   = true;
            AllowSaveActions = false;
            IEnumerable <MapPathInfo>      pathInfos = this.puzzleGenerator.GeneratePathInfos();
            ObservableCollection <MapItem> items     = new ObservableCollection <MapItem>();

            foreach (MapPathInfo pathInfo in pathInfos)
            {
                MapPath copiedPath = (MapPath)pathInfo.Path.Clone();
                copiedPath.Attributes.Add(new MapItemAttribute()
                {
                    Name = "RealLocation", Type = typeof(GeoPoint), Value = pathInfo.RealLocation
                });
                Vector delta = CoordPointToScreenPoint(pathInfo.GameCenter) - CoordPointToScreenPoint(pathInfo.RealCenter);
                ActiveItems = new ObservableCollection <MapItem>()
                {
                    copiedPath
                };
                TranslateItemsCommand.Execute(delta);
                items.Add(copiedPath);
            }
            Items = items;
            ZoomToRegion.Execute(new object[] { new GeoPoint(15, -180), new GeoPoint(-62, -45), 0.05 });
            AllowSaveActions = true;
            this.isLoading   = false;
        }
Exemplo n.º 14
0
    void Reset()
    {
        goal = movable.Cell;
        path = new MapPath(movable.Cell, Color.red);

        foreach (Pair <Farmer, Cell> farmer in farmers)
        {
            farmer.First.Detach();
        }

        farmers = new List <Pair <Farmer, Cell> >();
        action  = MoveAction.SetDestination;

        foreach (GameObject go in farmerTargets)
        {
            GameObject.Destroy(go);
        }

        foreach (Cell cell in Cell.cells)
        {
            cell.Reset();
        }

        farmerTargets = new List <GameObject>();
    }
Exemplo n.º 15
0
        static void Main(string[] args)
        {
            // Display help.
            if ((args.Length == 0) ||
                (args[0] == "-?") ||
                (args[0] == "/?") ||
                (args[0].ToLower() == "help"))
            {
                OutputHelp();
                return;
            }

            // Forgot to specify solution path.
            if (args.Length < 2)
            {
                Console.WriteLine("No destination image path specified.");
                return;
            }

            // Collect file paths.
            string sourcePath = args[0];
            string outputPath = args[1];

            // Optional strategy option specified.
            string strategyOption = null;

            if (args.Length > 2)
            {
                strategyOption = args[2];
            }

            // Attempt to load the image.
            Bitmap sourceImage;

            try
            {
                sourceImage = new Bitmap(sourcePath);
            }
            catch (Exception)
            {
                Console.WriteLine("Source file is not a valid image format.");
                return;
            }

            // TODO: Allow other strategies if time allows.
            Map     map  = new Map(sourceImage);
            MapPath path = PathFinder.FindPath(map, Strategies.BreadthFirst, strategyOption);

            // No solution found.
            if (path == null)
            {
                Console.WriteLine("No path could be found to solve the maze.");
                Console.WriteLine("Are you using the correct colors?");
                return;
            }

            PathFinder.OutputBitmap(path, map, outputPath);
            System.Console.WriteLine("Solution saved successfully to " + outputPath);
        }
    public bool validMapPath(MapPath mapPath)
    {
        //TODO: check more conditions for validity
        float length = mapPath.Length;

        return(length >= minLength &&
               length <= maxLength);
    }
 public static void PlayCards(string playerName, string returnPoint, string returnKnot)
 {
     CardGameInitializer.playerName  = playerName;
     CardGameInitializer.returnPoint = MapPath.WithString(returnPoint);
     CardGameInitializer.returnKnot  = returnKnot;
     Time.timeScale = 1.0f;
     pendingGame    = true;
 }
Exemplo n.º 18
0
        /// <summary>
        /// Save a solved map to an image file.
        /// </summary>
        /// <param name="path"></param>
        /// <param name="map"></param>
        /// <param name="outputPath"></param>
        public static void OutputBitmap(
            MapPath path,
            Map map,
            string outputPath)
        {
            // Get pixels from original map data.
            byte[] pixels = path.TraceOverMap(map);

            // Output the bitmap.
            string        extension = Path.GetExtension(outputPath);
            BitmapEncoder encoder;

            switch (extension)
            {
            default:
                encoder = new BmpBitmapEncoder();
                break;

            case ".png":
                encoder = new PngBitmapEncoder();
                break;

            case ".gif":
                encoder = new GifBitmapEncoder();
                break;

            case ".tif":
            case "tiff":
                encoder = new TiffBitmapEncoder();
                break;

            case ".jpg":
            case "jpeg":
                encoder = new JpegBitmapEncoder();
                break;

            case ".wmp":
                encoder = new WmpBitmapEncoder();
                break;
            }

            Console.WriteLine(extension);

            // TODO: Figure out why files have no compression.
            int          stride       = map.Width * Map.BytesPerPixel;
            BitmapSource bitmapSource = BitmapSource.Create(
                map.Width, map.Height,
                96, 96,
                PixelFormats.Bgra32, null, pixels, stride);

            encoder.Frames.Add(BitmapFrame.Create(bitmapSource));

            using (FileStream filestream = new FileStream(outputPath, FileMode.Create))
            {
                encoder.Save(filestream);
            }
        }
Exemplo n.º 19
0
        public void SavePath(MapPath path)
        {
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }

            paths.Add(path);
        }
Exemplo n.º 20
0
 internal static void ShowMapPath()
 {
     if (!LoadedFiles.IsLoadedMap(out string MapPath))
     {
         SendMsg(true, "로드된 맵이 없습니다.");
         return;
     }
     SendMsg(true, $"현재 로드된 맵 경로: {MapPath.Substring(MapPath.IndexOf(@"\Warcraft III\Maps\") + 14)}");
 }
 public MapPathInfo(MapPath path, GeoPoint realLocation, GeoPoint realCenter, GeoPoint gameCenter)
 {
     this.path         = path;
     this.realLocation = realLocation;
     this.realCenter   = realCenter;
     this.gameCenter   = gameCenter;
     this.name         = path.Attributes["NAME_LONG"].Value.ToString();
     this.captial      = path.Attributes["CAPITAL"].Value.ToString();
 }
Exemplo n.º 22
0
 public MapPath(MapPath toCopy)
 {
     path = new List<MapNode>();
     for (int i = 0; i < toCopy.path.Count; i++) {
         path.Add(toCopy.path[i]);
     }
     length = toCopy.length;
     combinedRisk = toCopy.combinedRisk;
 }
Exemplo n.º 23
0
        WeightedItem ProcessPath(MapPath mapPath)
        {
            IList <IList <double> > segmentsWeights = new List <IList <double> >();

            foreach (MapPathSegment segment in mapPath.Segments)
            {
                segmentsWeights.Add(ProcessSegment(segment));
            }
            return(new WeightedItem(mapPath, segmentsWeights));
        }
 void MoveItemToSolveLayer(MapPath mapPath)
 {
     Items.Remove(mapPath);
     SolvedItems.Add(mapPath);
     ActiveItem = mapPath;
     if (Items.Count == 0)
     {
         ShowWinMessage();
     }
 }
Exemplo n.º 25
0
        //----------------------------------------------------------------------------
        //              DoMove
        //----------------------------------------------------------------------------

        #region DoMove
        /// <summary>
        /// Called by a movement controller to move the IHasTurn to the end of path
        /// </summary>
        public void DoMove(IHasTurn hasTurn, MapPath path)
        {
            MyHasTurn        = hasTurn;
            ContentTransform = MyHasTurn.MyHexContents.ContentTransform;
            Path             = path;
            StopAllCoroutines();

            RemoveStartLocationFromPath();

            StartCoroutine(MoveToDestination());
        }
Exemplo n.º 26
0
        private void DrawPath(MapPath mapPath, Pen pen)
        {
            // Draw map path points
            foreach (MapPoint point in mapPath.Points)
            {
                DrawPoint(point.X, point.Y, pen);
            }

            DrawNavigatorPoints(mapPath);

            pbMap.Refresh();
        }
Exemplo n.º 27
0
        //----------------------------------------------------------------------------
        //              DoMove
        //----------------------------------------------------------------------------

        /// <summary>
        /// Revert the hexagons to inert <para/>
        /// Then find a path for CurrentIHasTurn to endLocation, and pass that path to Movement
        /// </summary>
        public void DoMove(IHexagon endLocation)
        {
            foreach (IHexagon hex in HexesInRange)
            {
                hex.Interaction.MakeUnselectable();
            }


            MapPath myMapPath = MyMapPathfinding.GeneratePath(CurrentIHasTurn.MyHexContents.Location, endLocation);

            MyMovement.DoMove(CurrentIHasTurn, myMapPath);
        }
Exemplo n.º 28
0
    public override MapPath generate(PathGenerationRequirements pgp)
    {
        this.pgp = pgp;
        mapPath  = new MapPath(pgp.middle);
        //Get build dir
        Vector2 buildDir = pgp.startPos - pgp.endPos;

        if (pgp.forceRectangularPaths)
        {
            if (Mathf.Abs(buildDir.x) > Mathf.Abs(buildDir.y))
            {
                //Make horizontal
                buildDir.y = 0;
            }
            else
            {
                //Make vertical
                buildDir.x = 0;
            }
        }
        //Add initial point
        Vector2 buildPos = generatePathPos(mapPath.Start, buildDir);

        mapPath.addToStart(buildPos, true);
        //Add middle points
        Vector2 prevBuildDir = buildDir;

        for (int i = 0; i < segmentCount - 3; i++)
        {
            int safetyEject = 100;
            do
            {
                buildDir = generateNewDirection(prevBuildDir);
                buildPos = generatePathPos(mapPath.Start, buildDir);
                safetyEject--;
                if (safetyEject == 0)
                {
                    Debug.Log($"Safety eject! buildPos: {buildPos}");
                    break;
                }
            }while (!validPosition(buildPos));
            prevBuildDir = buildDir;
            mapPath.addToStart(buildPos, true);
        }
        //Add second to last point
        mapPath.addToStart(new Vector2(pgp.startPos.x, mapPath.Start.y), true);
        //Add last point
        mapPath.addToStart(pgp.startPos, true);
        //Return
        return(mapPath);
    }
Exemplo n.º 29
0
        List <WeightedItem> ProcessItems(IEnumerable <MapItem> items)
        {
            List <WeightedItem> weightedItems = new List <WeightedItem>();

            foreach (MapItem mapItem in items)
            {
                MapPath mapPath = mapItem as MapPath;
                if (mapPath != null)
                {
                    weightedItems.Add(ProcessPath(mapPath));
                }
            }
            return(weightedItems);
        }
Exemplo n.º 30
0
        private void DrawNavigatorPoints(MapPath mapPath)
        {
            if (mapPath.Points.Count < selectedNavigatorPath.Points.Count)
            {
                return;
            }

            int difference = (int)Math.Floor((double)mapPath.Points.Count / selectedNavigatorPath.Points.Count);

            for (int i = 0; i < mapPath.Points.Count; i = i + difference)
            {
                DrawPoint(mapPath.Points[i].X, mapPath.Points[i].Y, redPen);
            }
        }
Exemplo n.º 31
0
        public MapPath AddPath(MapLayer layer, IEnumerable <MapPointLatLon> points, Color color)
        {
            if (!_layers.Contains(layer))
            {
                return(null);
            }
            var path = new MapPath(points);

            layer.Paths.Add(path);
            _pathColors.Add(path, color);
            _pathLayers.Add(path, layer);

            return(path);
        }
Exemplo n.º 32
0
        public void ProcessWorksWithoutData()
        {
            List <MapItem> items = new List <MapItem>();

            this.calculator.Process(items);
            Assert.AreEqual(0, this.calculator.Weights.Count);
            Assert.AreEqual(0, this.calculator.WeightedItems.Count);

            MapPath mapPath1 = new MapPath();

            items.Add(mapPath1);
            this.calculator.Process(items);
            Assert.AreEqual(0, this.calculator.Weights.Count);
            Assert.AreEqual(1, this.calculator.WeightedItems.Count);
        }
Exemplo n.º 33
0
    private IEnumerator TravelAlongMapPathRoutine(MapPath mapPath)
    {
        isSailing = true;
        CameraControl.Instance.AllowScrolling = false;

        NodeConnection connection;
        for (int i = 1; i < mapPath.path.Count; i++) {
            connection = currentPort.GetConnectionToNode(mapPath.path[i]);
            yield return StartCoroutine(TravelToPortRoutine(mapPath.path[i], connection));
            yield return new WaitForSeconds(0.1f);
        }

        isSailing = false;
        CameraControl.Instance.AllowScrolling = true;
    }
Exemplo n.º 34
0
    public static MapPath GetMapPath(MapNode fromNode, MapNode toNode)
    {
        //Debug.Log("GetMapPath!");

        //create a path to begin exploring
        MapPath bestPath = new MapPath();
        bestPath.AddNode(fromNode);

        //create a list of possible paths
        List<MapPath> paths = new List<MapPath>();
        paths.Add(bestPath);

        List<NodeConnection> newConnections;
        MapNode currentNode;
        MapNode tempNode;
        while (bestPath != null) {

            //Debug.Log ("-----------------------START LOOP!");

            if (bestPath.IsComplete(fromNode, toNode)) {
                //Debug.Log("Found Complete path!");
                break;
            }

            currentNode = bestPath.EndNode;
            newConnections = currentNode.GetConnections();

            Debug.Log("Current node "+currentNode.name);

            for (int i = 0; i < newConnections.Count; i++)
            {
                tempNode = newConnections[i].GetOppositeEnd(currentNode);
                if (!bestPath.path.Contains(tempNode)) {
                    //Debug.Log("Added new path!");
                    MapPath newPath = new MapPath(bestPath);
                    newPath.AddNode(tempNode);
                    paths.Add(newPath);
                }
            }

            paths.Remove(bestPath);
            bestPath = GetBestPath(paths);
        }

        return bestPath;
    }
Exemplo n.º 35
0
        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="engine">The rewriting engine.</param>
        /// <param name="rawUrl">The initial, raw URL.</param>
        /// <param name="httpContext">The HTTP context facade.</param>
        /// <param name="configurationManager">The configuration manager facade.</param>
        internal RewriteContext(
            RewriterEngine engine,
            string rawUrl,
            IHttpContext httpContext,
            IConfigurationManager configurationManager)
        {
            if (engine == null)
            {
                throw new ArgumentNullException("engine");
            }
            if (httpContext == null)
            {
                throw new ArgumentNullException("httpContext");
            }
            if (configurationManager == null)
            {
                throw new ArgumentNullException("configurationManager");
            }

            _engine = engine;
            _configurationManager = configurationManager;
            _location = rawUrl;
            _method = httpContext.HttpMethod;
            _mapPath = httpContext.MapPath;

            // Initialise the Properties collection from all the server variables, headers and cookies.
            foreach (string key in httpContext.ServerVariables.AllKeys)
            {
                _properties.Add(key, httpContext.ServerVariables[key]);
            }
            foreach (string key in httpContext.RequestHeaders.AllKeys)
            {
                _properties.Add(key, httpContext.RequestHeaders[key]);
            }
            foreach (string key in httpContext.RequestCookies.AllKeys)
            {
                _properties.Add(key, httpContext.RequestCookies[key].Value);
            }
        }
Exemplo n.º 36
0
    public void FromJson(Hashtable json)
    {
        ArrayList nodes = json["Nodes"] as ArrayList;

        foreach(Hashtable nodeHash in nodes) {
            XY coord = new XY(nodeHash["Coord"] as Hashtable);
            MapRoom room = new MapRoom(nodeHash["Room"] as Hashtable);

            Graph.AddNode(coord, room);
        }

        ArrayList edges = json["Edges"] as ArrayList;

        foreach(Hashtable edgeHash in edges) {
            MapNode from = Graph.GetNodeByCoord(new XY(edgeHash["From"] as Hashtable));
            MapNode to = Graph.GetNodeByCoord(new XY(edgeHash["To"] as Hashtable));
            MapPath path = new MapPath(edgeHash["Path"] as Hashtable);

            Graph.AddEdge(from, to, path);
        }

        Entrance = Graph.GetNodeByCoord(new XY(json["Entrance"] as Hashtable));
    }
Exemplo n.º 37
0
 /// <summary>
 /// Default constructor.
 /// </summary>
 public HttpContextFacade()
 {
     _mapPath = new MapPath(InternalMapPath);
 }
Exemplo n.º 38
0
    private void ShowTravelInfo()
    {
        path = NodeNavigator.GetMapPath(ShipPositionMarker.Instance.currentPort, mapNode);

        //label
        travelInfoLabel.text = (locationData != null && path != null) ? "TRAVEL TO "+locationData.name.ToUpper() : "";

        if (path != null)
        {
            System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();

            //distance & route info
            stringBuilder.AppendLine(string.Format("DISTANCE:\t{0} nautical miles / {1} days", Mathf.CeilToInt(path.length), Mathf.CeilToInt(path.length / 50f)));
            stringBuilder.AppendLine(string.Format("ROUTE:\t{0}", path.ToString()));
            stringBuilder.AppendLine();

            stringBuilder.AppendLine(string.Format("RISK:\t{0}", ConvertRiskValueToColoredText(path.GetRiskAverage())));

            travelInfo.text = stringBuilder.ToString();
        }
        else
            travelInfo.text = "";
    }
Exemplo n.º 39
0
 public void TravelToPort(MapPath mapPath)
 {
     StartCoroutine(TravelAlongMapPathRoutine(mapPath));
 }
Exemplo n.º 40
0
 /// <summary>
 ///     Default constructor.
 /// </summary>
 public HttpContextFacade()
 {
     _mapPath = InternalMapPath;
 }
Exemplo n.º 41
0
 public void AddConnectedPath(MapPath path)
 {
     if (connectedPaths == null)
     {
         connectedPaths = new List<MapPath>();
     }
     connectedPaths.Add(path);
 }
    void Update()
    {
        if (GameManager.Instance.Paused) {
            return;
        }

        while (occupiedCities.Count > 0 && occupiedCities.Peek().occupier != civName) {
            occupiedCities.Pop();
            elapsedTime = 0f;
        }

        if (occupiedCities.Count == 0) {
            return;
        }

        if (occupiedCities.Peek() != selectedCity) {
            elapsedTime = 0;
            phase = 0;
            selectedCity = occupiedCities.Peek();
            MapPoint[] connectedCities = selectedCity.ConnectedCities;
            targetCity = connectedCities[Random.Range(0, connectedCities.Length-1)];

            civLimit = 300 + Random.Range(0,100);
            soldierLimit = 200 + Random.Range(0,100);
            diffLimt = 1f + Random.Range(-0.5f, 1f);

            foreach (MapPath path in selectedCity.ConnectedPaths) {
                if (path.endPointA == targetCity || path.endPointB == targetCity) {
                    connectingPath = path;
                }
            }
        }

        elapsedTime += Time.deltaTime;

        if (targetCity.occupier == "") {
            // Train Settlers Until Limit
            if (phase == 0) {
                if (selectedCity.civilians >= civLimit) {
                    ++phase;
                }
                if (elapsedTime > selectedCity.civDelay && selectedCity.food > 0) {
                    elapsedTime -= selectedCity.civDelay;
                    selectedCity.ConvertFoodToCiv();
                }
            }
            // Send Settlers Until Limit
            else if (phase == 1) {
                elapsedTime = 0;
                if (selectedCity.civilians > 20 + Random.Range(0, 30)) {
                    selectedCity.SendCivsToTarget(targetCity);
                }
                else {
                    ++phase;
                }
            }
            else {
                phase = 0;
            }
        }
        else if (targetCity.occupier != civName) {
            // Train Settlers Until Limit
            if (phase == 0) {
                if (selectedCity.civilians >= 50) {
                    ++phase;
                }
                if (elapsedTime > selectedCity.civDelay && selectedCity.food > 0) {
                    elapsedTime -= selectedCity.civDelay;
                    selectedCity.ConvertFoodToCiv();
                }
            }
            // Train Soldiers Until Limit
            else if (phase == 1) {
                if (selectedCity.soldiers >= Random.Range(30,50)) {
                    ++phase;
                }
                if (elapsedTime > selectedCity.armyDelay && selectedCity.food > 0 && selectedCity.civilians > 50) {
                    elapsedTime -= selectedCity.armyDelay;
                    selectedCity.ConvertCivToSoldier();
                }
                else if (elapsedTime > selectedCity.armyDelay && selectedCity.food > 0 && selectedCity.food > 1) {
                    elapsedTime -= selectedCity.armyDelay;
                    selectedCity.ConvertFoodToSoldier();
                }
            }
            // Train Settlers Until Limit or Path Difficulty Limit
            else if (phase == 2) {
                if (selectedCity.civilians >= civLimit || connectingPath.difficulty < diffLimt) {
                    ++phase;
                }
                if (elapsedTime > selectedCity.civDelay && selectedCity.food > 0) {
                    elapsedTime -= selectedCity.civDelay;
                    selectedCity.ConvertFoodToCiv();
                }
            }
            // Send Settlers Until Path Difficulty Limit
            else if (phase == 3) {
                elapsedTime = 0;
                if (selectedCity.civilians > 20 && connectingPath.difficulty >= diffLimt) {
                    selectedCity.SendCivsToTarget(targetCity);
                }
                else if (connectingPath.difficulty < diffLimt) {
                    ++phase;
                }
                else {
                    if (Random.Range(0f,1f) > 0.5f) {
                        phase = 0;
                    }
                    else {
                        ++phase;
                    }
                }
            }
            // Train Soldiers Until Limit
            else if (phase == 4) {
                if (selectedCity.soldiers >= soldierLimit) {
                    ++phase;
                }
                if (elapsedTime > selectedCity.armyDelay && selectedCity.food > 0 && selectedCity.civilians > 50) {
                    elapsedTime -= selectedCity.armyDelay;
                    selectedCity.ConvertCivToSoldier();
                }
            }
            // Send Soldiers Until Limit
            else if (phase == 5) {
                elapsedTime = 0;
                if (selectedCity.soldiers > 20 + Random.Range(0, 30)) {
                    if (selectedCity.food > 0) {
                        selectedCity.SendSoldiersToTarget(targetCity);
                    }
                }
                else {
                    ++phase;
                }
            }
            else {
                phase = 0;
            }
        }
        else {
            // Shuffle Occupied Cities List
            MapPoint[] cityArray = occupiedCities.ToArray();
            for (int i=1; i<occupiedCities.Count; i++) {
                int j = Random.Range(0,i);

                MapPoint tempCity = cityArray[i];
                cityArray[i] = cityArray[j];
                cityArray[j] = tempCity;
            }
            occupiedCities = new Stack<MapPoint>(cityArray);
        }
    }