public void Y座標が1大きい座標は隣り合っている()
    {
      var gp1 = new GridPoint(1, 2);
      var gp2 = new GridPoint(1, 3);

      gp1.IsNeighborOf(gp2).Is(true);
    }
예제 #2
0
    private const float GPPU = 1f; // Grid Points Per Unit.

    #endregion Fields

    #region Methods

    // Use this for initialization
    public void init(Rect bounds, int partitions)
    {
        // Make our new bounds smaller than the given bounds by one partition length because shortcuts.
        this.bounds = bounds;

        // Set up our partition list of entities.
        entityPartitions = new List<PhysicsEntity>[partitions, partitions];
        for (int x = 0; x < partitions; x++)
        {
            for (int y = 0; y < partitions; y++)
            {
                entityPartitions[x,y] = new List<PhysicsEntity>();
            }
        }

        // set up our array of gridpoints.
        gridPoints = new GridPoint[(int)(bounds.width * GPPU), (int)(bounds.height * GPPU)];
        // Set up our array of vertices that we will be passing in to the grid mesh.
        Vector3[] meshPoints = new Vector3[gridPoints.GetLength(0) * gridPoints.GetLength(1)];
        int index = 0;

        for (int y = 0; y < gridPoints.GetLength(1); y++)
        {
            for (int x = 0; x < gridPoints.GetLength(0); x++)
            {
                GridPoint point = new GridPoint();
                point.init(new Vector3((float)x / GPPU, 0, (float)y / GPPU));
                gridPoints[x,y] = point;
                meshPoints[index++] = point.position;
            }
        }

        meshFilter.mesh = makeGrid(meshPoints, gridPoints.GetLength(0), gridPoints.GetLength(1));
    }
    public void Y座標が違う格子点は同じ座標を持たない()
    {
      var gp1 = new GridPoint(1, 2);
      var gp2 = new GridPoint(1, 3);

      gp1.HasSameCoordinatesWith(gp2).Is(false);
    }
    public void X座標とY座標が共に1大きい座標は隣り合っていない()
    {
      var gp1 = new GridPoint(1, 2);
      var gp2 = new GridPoint(2, 3);

      gp1.IsNeighborOf(gp2).Is(false);
    }
    public void Y座標が1大きくX座標が2大きい座標は隣り合っていない()
    {
      var gp1 = new GridPoint(1, 2);
      var gp2 = new GridPoint(3, 3);

      gp1.IsNeighborOf(gp2).Is(false);
    }
    public void 同じ格子点は同じ座標を持つ()
    {
      var gp1 = new GridPoint(1, 2);
      var gp2 = new GridPoint(1, 2);

      gp1.HasSameCoordinatesWith(gp2).Is(true);
    }
예제 #7
0
 public GridRect(GridPoint location, double width, double height)
 {
     _point1 = location;
     _point2 = new GridPoint(location.X + width, location.Y);
     _point3 = new GridPoint(location.X, location.Y + height);
     _point4 = new GridPoint(location.X + width, location.Y + height);
 }
예제 #8
0
 public GridRect(double x, double y, double width, double height)
 {
     _point1 = new GridPoint(x, y);
     _point2 = new GridPoint(x + width, y);
     _point3 = new GridPoint(x, y + height);
     _point4 = new GridPoint(x + width, y + height);
 }
    public void 同じ座標は隣り合っていない()
    {
      var gp1 = new GridPoint(1, 2);
      var gp2 = new GridPoint(1, 2);

      gp1.IsNeighborOf(gp2).Is(false);
    }
예제 #10
0
 public DirectionPoint(Vector3 start, float directiondegrees, float MaxRange=25f)
 {
     StartingPoint=start;
              DirectionDegrees=directiondegrees;
              Range=MaxRange;
              Center=start;
              EndingPoint=start;
              update_(start);
 }
예제 #11
0
 public static GridIndex GetPointGridIndex(GridPoint gridPoint)
 {
     GridIndex result = new GridIndex();
     result.Index1 = gridPoint.TranformGridIndex(GridConfig.LEVEL1_X_GRID, GridConfig.LEVEL1_Y_GRID, GridConfig.Level1XCellSpan, GridConfig.Level1YCellSpan);
     result.Index2 = gridPoint.TranformGridIndex(GridConfig.LEVEL2_X_GRID, GridConfig.LEVEL2_Y_GRID, GridConfig.Level2XCellSpan, GridConfig.Level2YCellSpan);
     result.Index3 = gridPoint.TranformGridIndex(GridConfig.LEVEL3_X_GRID, GridConfig.LEVEL3_Y_GRID, GridConfig.Level3XCellSpan, GridConfig.Level3YCellSpan);
     result.Index4 = gridPoint.TranformGridIndex(GridConfig.LEVEL4_X_GRID, GridConfig.LEVEL4_Y_GRID, GridConfig.Level4XCellSpan, GridConfig.Level4YCellSpan);
     return result;
 }
 // Update is called once per frame
 void OnDrawGizmosSelected()
 {
     if(snap){
         int loc = ConvertLoc(transform.position);
         gridLoc = loc;
         transform.position = myGrid.grids[gridI].grid[loc].loc;
         point = myGrid.grids[gridI].grid[loc];
     }
 }
예제 #13
0
		private bool InitializeReachable(GridPoint pos, int reachableCount) {
			if ((reachableMap[pos.X,pos.Y] == 0 || reachableMap[pos.X, pos.Y] > reachableCount) && target.IsWalkable(pos)) {
				reachables.Push(pos);
				reachableMap[pos.X,pos.Y] = reachableCount;
				return true;
			} else {
				return false;
			}
		}
예제 #14
0
        public NavigationController()
        {
            //Debug.Log("Creating navigation grid...");
            _navGrid = new GridPoint[GRID_HEIGHT, GRID_WIDTH];
            for (int h = 0; h < GRID_HEIGHT; h++)
                for (int w = 0; w < GRID_WIDTH; w++)
                    _navGrid[h, w] = new GridPoint(h, w);

            _pather = new SpatialAStar<GridPoint, UnitMoverType>(_navGrid);
        }
예제 #15
0
    /////////////////////
    /// Base Constructors
    ///
    public GridSearchAStar(GridMap grid, GridPoint source, GridPoint destination)
        : base(grid)
    {
        this.source = source;
        this.destination = destination;

        explored = new Dictionary<int, GridState>();
        frontier = new PriorityQueue<GridState>();
        path = new GridPath();
    }
예제 #16
0
		public AStarPathFinder(SearchTarget searchTarget, GridPoint goalPos, GridPoint startPos, int limitCost = int.MaxValue) {
			this.searchTarget = searchTarget;
			this.startPos = startPos;
			this.goalPos = goalPos;
			this.limitCost = limitCost;
			this.path = null;
			sortedOpens.Clear();

			Calculate();
		}
예제 #17
0
		public IEnumerable<GridPoint> GetAllReachable(GridPoint pos) {
			int level = reachableMap[pos.X, pos.Y];
			for (int x=0; x < target.SizeX; x++) {
				for(int y=0; y<target.SizeY;y++) {
					if(reachableMap[x, y] == level) {
						yield return new GridPoint(x, y);
					}
				}
			}
		}
예제 #18
0
        public GPQuadrant(GridPoint[] points, Vector3 GPCenteringVector, GridPoint endpoint)
        {
            this.ContainedPoints.AddRange(points);
            this.StartPoint = GPCenteringVector;
            this.CornerPoint = endpoint.Clone();

            if (points.Length > 0)
            {
                this.AverageAreaVectorZ = this.ContainedPoints.Sum(gp => gp.Z) / this.ContainedPoints.Count;
                this.AreaIsFlat = (this.AverageAreaVectorZ == this.ContainedPoints.First().Z);
            }
        }
예제 #19
0
        private void update_(Vector3 startV3)
        {
            //raycast to test how far we could go..
                     Vector3 MaxRangeTestVector3=MathEx.GetPointAt(startV3, Range, MathEx.ToRadians(DirectionDegrees));

                     Vector2 RaycastTestV2;
                     //we use main grid providers raycast to test since we are looking at how far we can travel and not if anything is blocking us.
                     if (Navigation.MGP.Raycast(startV3.ToVector2(), MaxRangeTestVector3.ToVector2(), out RaycastTestV2))
                     {//Set our endpoint at the Hit point
                          MaxRangeTestVector3=RaycastTestV2.ToVector3();
                          MaxRangeTestVector3.Z=Navigation.MGP.GetHeight(MaxRangeTestVector3.ToVector2()); //adjust height acordingly!
                     }
                     Range=Vector3.Distance2D(ref startV3, ref MaxRangeTestVector3);

                     //lets see if we can stand here at all?
                     if (!Navigation.MGP.CanStandAt(MaxRangeTestVector3))
                     {

                          //just because raycast set our max range, we need to see if we can use that cell as a walking point!
                          if (!Navigation.CanRayCast(startV3, MaxRangeTestVector3, Zeta.Internals.SNO.NavCellFlags.AllowWalk))
                          {
                                //loop to find a walkable range.
                                float currentRange=Range-2.5f;
                                float directionRadianFlipped=Navigation.FindDirection(MaxRangeTestVector3, startV3, true);
                                int maxTestAttempts=(int)(currentRange/2.5f);

                                for (int i=0; i<maxTestAttempts; i++)
                                {
                                     Vector3 newtestPoint=MathEx.GetPointAt(MaxRangeTestVector3, currentRange, directionRadianFlipped);
                                     newtestPoint.Z=Navigation.MGP.GetHeight(newtestPoint.ToVector2());//update Z
                                     if (Navigation.CanRayCast(startV3, newtestPoint, Zeta.Internals.SNO.NavCellFlags.AllowWalk))
                                     {
                                          MaxRangeTestVector3=newtestPoint;
                                          break;
                                     }

                                     if (currentRange-2.5f<=0f) break;
                                     currentRange=-2.5f;
                                }
                                Range=currentRange;
                          }

                     }

                     EndingPoint=MaxRangeTestVector3;
                     StartingPoint=startV3;
                     Range=startV3.Distance2D(MaxRangeTestVector3); //(float)GridPoint.GetDistanceBetweenPoints(StartingPoint, EndingPoint);
                     Center=MathEx.GetPointAt(startV3, Range/2, MathEx.ToRadians(DirectionDegrees));
        }
예제 #20
0
    private static int maxChecksPerFrame = 1000; //In case of error states

    #endregion Fields

    #region Methods

    public static GridPoint[] Path(GridPoint start, GridPoint goal)
    {
        List<PathingNode> closedSet = new List<PathingNode> ();
        List<PathingNode> openSet = new List<PathingNode> ();

        PathingNode currNode = new PathingNode (start);
        openSet.Add (currNode);

        int count = 0;
        while (openSet.Count!=0 && count<maxChecksPerFrame) {
            count++;
            currNode=openSet[0];

            foreach(PathingNode node in openSet){
                if(node.GetFScore(goal)<currNode.GetFScore(goal)){
                    currNode = node;
                }
            }
            if(currNode.loc.transform.position==goal.transform.position){
                return GetPathFromNode(currNode);
            }
            else{

                openSet.Remove(currNode);
                closedSet.Add(currNode);

                List<GridPoint> moves = GetPossibleNextPointsFromPosition(currNode.loc);

                foreach(GridPoint move in moves){
                    PathingNode potentialNode = new PathingNode(move,currNode);

                    if(closedSet.Contains(potentialNode)){
                    }
                    else if(openSet.Contains(potentialNode)){
                        int index = openSet.IndexOf(potentialNode);
                        if(openSet[index].g_score > potentialNode.g_score){
                            openSet[index]=potentialNode;
                        }
                    }
                    else{
                        openSet.Add(potentialNode);
                    }
                }
            }

        }
        return null;
    }
예제 #21
0
 UPath BackTrack(int startLoc, int endLoc, int[] lGridLookup, GridPoint[] lGrid)
 {
     int pathSize = 1;
     int loc = endLoc;
     while(loc != startLoc){
         loc = lGrid[lGridLookup[loc]].parent;
         pathSize++;
     }
     UPath mp = new UPath();
     mp.list = new int[pathSize];
     loc = endLoc;
     for(int x = pathSize-1; x >= 0; x--){
         mp.list[x] = loc;
         loc = lGrid[lGridLookup[loc]].parent;
     }
     return mp;
 }
예제 #22
0
    /// <summary>
    /// Calculates the shortest surface distance between two points on a 3D cube.
    /// </summary>
    /// <returns> The distance between the two points</returns>
    private static int CalculateShortestSurfaceDistance(GridPoint start, GridPoint end)
    {
        // CASE 1: start and end point are on the same face.
        if (start.face == end.face)
        {
            return(CalculateShortestDistance(start, end));
        }

        // CASE 2: end point is on a face that is connected to the start point.
        if (IsConnectedFace(start.face, end.face))
        {
            return(ConnectedFaceDistance(start, end));
        }

        // CASE 3: start and end point are on opposing faces.
        return(OpposingFaceDistance(start, end));
    }
예제 #23
0
        public void TestClone()
        {
            var grid = new BimaruGrid(1, 2);
            var p0   = new GridPoint(0, 0);
            var p1   = new GridPoint(0, 1);

            grid[p0] = BimaruValue.SHIP_SINGLE;
            grid[p1] = BimaruValue.UNDETERMINED;

            BimaruGrid clonedGrid = (BimaruGrid)grid.Clone();

            grid.AssertEqual(clonedGrid);

            grid[p1] = BimaruValue.SHIP_SINGLE;

            Assert.AreEqual(BimaruValue.UNDETERMINED, clonedGrid[p1]);
        }
예제 #24
0
        private void SetShipMiddleNeighbours(IGame game, GridPoint pointShipMiddle, DirectionType directionShipMiddle)
        {
            foreach (var direction in Directions.GetAllDirections())
            {
                var constraint = direction.GetDirectionType() == directionShipMiddle ?
                                 BimaruValueConstraint.SHIP :
                                 BimaruValueConstraint.WATER;

                // Skip set if constraint already satisfied
                var pointInDirection = pointShipMiddle.GetNextPoint(direction);
                if (!constraint.IsSatisfiedBy(game.Grid[pointInDirection]))
                {
                    BimaruValue valueToSet = constraint.GetRepresentativeValue();
                    game.Grid[pointInDirection] = valueToSet;
                }
            }
        }
예제 #25
0
    MapPoint CreatePoint(GridPoint gp)
    {
        GameObject g = Instantiate(pointPrefab, gp.transform.position, Quaternion.identity);

        g.name = System.String.Format("MapPoint({0}, {1})", gp.posX, gp.posY);

        MapPoint mp = g.GetComponentInChildren <MapPoint>();

        mp.UseValueOf(gp);

        points[mp.posX - 1, mp.posY - 1] = mp;
//		Debug.Log(string.Format("points[{0}, {1}] is filled.", mp.posX - 1, mp.posY - 1));

        mp.transform.SetParent(pointParent);

        return(mp);
    }
예제 #26
0
        public void AddPointsToBoard_PopulatesBoard_GridPointsAddedWithCorrectPropertyValues()
        {
            var board = new GridPoint[2, 2];

            board.AddGridPointsToBoard();

            foreach (var point in board)
            {
                Assert.IsType <GridPoint>(point);
                Assert.Equal(0, point.AdjacentMineCount);
                Assert.Null(point.DisplayCharacter);
                Assert.False(point.IsMine);
                Assert.True(point.IsHidden);
                Assert.Equal(3, point.NeighbourCoordinates.Count);
            }
            Assert.Equal(4, board.Length);
        }
예제 #27
0
        public static IEnumerable <GridPoint> GetPointsOnLine(GridPoint from, GridPoint to)
        {
            var x0 = from.X;
            var x1 = to.X;
            var y0 = from.Y;
            var y1 = to.Y;

            var steep = Math.Abs(y1 - y0) > Math.Abs(x1 - x0);

            if (steep)
            {
                var t = x0;
                x0 = y0;
                y0 = t;
                t  = x1; // swap x1 and y1
                x1 = y1;
                y1 = t;
            }
            if (x0 > x1)
            {
                var t = x0;
                x0 = x1;
                x1 = t;
                t  = y0; // swap y0 and y1
                y0 = y1;
                y1 = t;
            }
            var dx    = x1 - x0;
            var dy    = Math.Abs(y1 - y0);
            var error = dx / 2;
            var ystep = (y0 < y1) ? 1 : -1;
            var y     = y0;

            for (var x = x0; x <= x1; x++)
            {
                yield return(new GridPoint((steep ? y : x), (steep ? x : y)));

                error = error - dy;
                if (error >= 0)
                {
                    continue;
                }
                y     += ystep;
                error += dx;
            }
        }
예제 #28
0
    void CheckConnectivity()
    {
        // remove any points that are not connected to root node
        Queue <GameObject> toVisit       = new Queue <GameObject>();
        List <GameObject>  removedPoints = new List <GameObject>();

        // establish connectivity
        toVisit.Enqueue(firstPoint);
        while (toVisit.Count > 0)
        {
            GridPoint p = toVisit.Dequeue().GetComponent <GridPoint>();
            p.Connect();
            if (p.forwardGameObject != null && !p.forwardGameObject.GetComponent <GridPoint>().Connected)
            {
                toVisit.Enqueue(p.forwardGameObject);
            }
            if (p.backGameObject != null && !p.backGameObject.GetComponent <GridPoint>().Connected)
            {
                toVisit.Enqueue(p.backGameObject);
            }
            if (p.leftGameObject != null && !p.leftGameObject.GetComponent <GridPoint>().Connected)
            {
                toVisit.Enqueue(p.leftGameObject);
            }
            if (p.rightGameObject != null && !p.rightGameObject.GetComponent <GridPoint>().Connected)
            {
                toVisit.Enqueue(p.rightGameObject);
            }
        }

        // check connectivity, adding points that are not connected to the list to be removed
        foreach (GameObject p in points)
        {
            if (!p.GetComponent <GridPoint>().CheckConnectivity())
            {
                removedPoints.Add(p);
            }
        }

        // remove points from main points list
        foreach (GameObject p in removedPoints)
        {
            points.Remove(p);
        }
    }
예제 #29
0
    public void Generate(bool randomSeed)
    {
        if (randomSeed)
        {
            seed = (int)System.DateTime.UtcNow.Ticks;             // Get unique seed based on system time
        }
        Random.InitState(seed);

        MathHelper.stopwatch.Restart();
        nodes = new List <BSPNode>();
        BSPNode rootNode = new BSPNode(0, 0, width - borderSize * 2, height - borderSize * 2, minNodeSize);

        splitBSPNode(rootNode);

        gridPoints = new GridPoint[width, height];
        for (int j = 0; j < height; j++)
        {
            for (int i = 0; i < width; i++)
            {
                GridPoint.Type type = GridPoint.Type.Grass;
                // Make sure nothing spawns right at the edge next to the wall
                if (i == 0 || i == width - 1 || j == 0 || j == height - 1)
                {
                    type = GridPoint.Type.Obstacle;
                }
                gridPoints[i, j] = new GridPoint(i, j, type);
            }
        }

        Build();

        // Set grid connections after placing objects so grid point types have been set
        for (int j = 0; j < height; j++)
        {
            for (int i = 0; i < width; i++)
            {
                setGridPointConnections(gridPoints[i, j]);
            }
        }

        roadGridPoints = GetGridPoints(GridPoint.Type.Path, GridPoint.Type.Pavement);

        MathHelper.stopwatch.Stop();
        Debug.LogFormat("Generated town (seed={0}) with {1} BSP nodes and {2} objects in {3}ms", seed, nodes.Count, objectContainer.childCount, (float)MathHelper.stopwatch.ElapsedTicks / System.TimeSpan.TicksPerMillisecond);
    }
예제 #30
0
        public static IList <GridPoint> GetPathToPoint(
            GridPoint robotPosition,
            GridPoint targetPoint,
            Dictionary <GridPoint, HullCellType> exploredPoints)
        {
            if (targetPoint == null)
            {
                return(new List <GridPoint>());
            }
            IList <GridPoint> GetNeighbors(GridPoint p)
            {
                List <GridPoint>  result    = new List <GridPoint>();
                IList <GridPoint> neighbors = GetAdjacentPoints(p);

                foreach (var n in neighbors)
                {
                    // Only include explored points in the path
                    // unless the neighbor is the target
                    if (exploredPoints.ContainsKey(n) &&
                        !HullCellType.Wall.Equals(exploredPoints[n]))
                    {
                        result.Add(n);
                    }
                    else if (targetPoint.Equals(n))
                    {
                        result.Add(n);
                    }
                }
                return(result);
            }

            int Heuristic(GridPoint p)
            {
                return(GridPoint.GetManhattanDistance(p, targetPoint));
            }

            var aStarResult = AStar.GetPath <GridPoint>(
                startPoint: robotPosition,
                endPoint: targetPoint,
                Heuristic: Heuristic,
                GetNeighbors: GetNeighbors,
                GetEdgeCost: (p1, p2) => { return(1); });

            return(aStarResult.Path);
        }
예제 #31
0
    void Update()
    {
        // Determines what the player clicked on
        if (Input.GetMouseButtonDown(0))
        {
            Ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            if (Physics.Raycast(Ray, out _raycastHit))
            {
                LastClickedObject = _raycastHit.transform.collider.gameObject;

                GridPoint maybeClicked = LastClickedObject.GetComponent<GridPoint>();

                if(maybeClicked!=null && maybeClicked.CanBuild()){
                    if(lastClickedGridPoint!=null){
                        lastClickedGridPoint.Deselect();
                    }

                    lastClickedGridPoint = maybeClicked;

                    lastClickedGridPoint.Select();
                }

            }
        }

        //Determine which tower to make
        for(int i = 0; i<TowerTypes.Length; i++){
            if(Input.GetKeyDown(towerkeys[i])){
                Tower t = TowerTypes[i].GetComponent<Tower>();
                if(lastClickedGridPoint.CanBuild() && Global.Instance.CanBuild(t) && !lastClickedGridPoint.HasTower()){
                    //TODO; build tower sound
                    lastClickedGridPoint.CreateTower(Global.Instance.CreateTower(TowerTypes[i], lastClickedGridPoint.transform.position+Vector3.up));
                }
                else if(lastClickedGridPoint.HasTower()){
                    //TODO; make can't make tower sound
                    lastClickedGridPoint.DestroyTower();
                    lastClickedGridPoint.CreateTower(Global.Instance.CreateTower(TowerTypes[i], lastClickedGridPoint.transform.position+Vector3.up));
                }
                else{
                    //TODO; Didn't work sound
                }
            }
        }
    }
    public GenericMovementBehavior(int moveSpeed, UnitMoverType moveType, GridPoint spawnPos = null)
    {
        _moveSpeed = moveSpeed;
        _moveType = moveType;
        _currentLocation =
        _targetLocation = null;

        if (spawnPos == null) _currentLocation = NavigationController.Instance.FirstTile;
        else _currentLocation = spawnPos;

        // pathing stuff
        _pathToTraverse = null;
        _pendingPath = null;
        _ratioAlongCurrentStep = 0f;
        _currentPathNode = null;
        _currentStepLength = 0.0f;
        _nodesRemaining = -1;
    }
예제 #33
0
    /// <summary>
    /// Initializes common values.  Do not override.
    /// </summary>
    public void Initialize(GridPoint start, GridPoint target)
    {
        Target = target;

        CurrentHealth = MaxHealth;
        CurrentSpeed = MaxSpeed;
        IsAlive = true;
        Accuracy = 1f;

        path = AStar.Path (start, target);

        if (onSpawn != null) {
            AudioSource.PlayClipAtPoint(onSpawn,transform.position);
        }

        //foreach (GridPoint pnt in path) {
        //}
    }
예제 #34
0
        public static IList <GridPoint> GetNewUnexploredPoints(
            GridPoint robotPosition,
            Dictionary <GridPoint, HullCellType> exploredPoints,
            Tree <GridPoint> unexploredPoints)
        {
            IList <GridPoint> result = new List <GridPoint>();

            for (int i = 1; i <= 4; i++)
            {
                var nextPoint = GetNextPoint(robotPosition, i);
                if (!exploredPoints.ContainsKey(nextPoint) &&
                    !unexploredPoints.Contains(nextPoint))
                {
                    result.Add(nextPoint);
                }
            }
            return(result);
        }
예제 #35
0
        public void TestMoveBackwardWhenObstacleExists()
        {
            var       obstacles        = new List <GridPoint>();
            GridPoint originalPosition = new GridPoint(2, 2);
            GridPoint expectedPosition = new GridPoint(2, 1);

            obstacles.Add(expectedPosition);
            var originalRoverDirection = CompassDirection.NORTH;

            terrainGrid.Setup(x => x.AdvanceSouth(originalPosition)).Returns(expectedPosition);

            var rover = new Rover(new TerrainGrid(10, 10, obstacles), originalPosition, originalRoverDirection);

            rover.MoveBackward();

            Assert.IsTrue(rover.CompassCurrentOrientation == originalRoverDirection);
            Assert.IsTrue(rover.CurrentGridPosition == originalPosition);
        }
예제 #36
0
 // Add or remove to the GridPoint's value while brush is activated
 private void OnTriggerStay(Collider other)
 {
     // Clamp the amount drawn/erased between 0 and 1
     if (draw)
     {
         this.Value = Mathf.Clamp(this.Value - dPaint * Time.deltaTime, 0f, 1f);
     }
     else
     {
         this.Value = Mathf.Clamp(this.Value + dPaint * Time.deltaTime, 0f, 1f);
     }
     // Make a build request
     if (OnPointValueChange != null)
     {
         GridPoint gp = this.GetComponent <GridPoint>();
         OnPointValueChange(ref gp);
     }
 }
예제 #37
0
    /// <summary>
    /// Finds all shells near a shell
    /// </summary>
    /// <returns></returns>
    private Dictionary <Shell, List <Shell> > FindNearestNeihbours()
    {
        Dictionary <Shell, List <Shell> > nearest = new Dictionary <Shell, List <Shell> >();

        foreach (Shell shell in SetAndTactShells)
        {
            nearest.Add(shell, new List <Shell>());

            GridPoint gp = shell.GridPoint;
            //The search radius for this iteration
            int r = 1;
            //keep searching at larger radii until at least 2 connections are found
            while (nearest[shell].Count < 2)
            {
            }
        }
        return(nearest);
    }
예제 #38
0
    public override bool Equals(object obj)
    {
        if (obj == null || GetType() != obj.GetType())
        {
            return(false);
        }

        GridPoint g = (GridPoint)(obj);

        if (this.x == g.x && this.y == g.y)
        {
            return(true);
        }
        else
        {
            return(false);
        }
    }
예제 #39
0
 /// <summary>
 /// Iterates each grid point in the world, calculating its settlement desirability
 /// We add each to a WeightRandomList <see cref="DesireWeightedGridpoints"/>.
 /// We add each grid point with a weight of its desirability
 /// </summary>
 private void FindGridPointsSettlementDesirability()
 {
     DesireWeightedGridpoints = new WeightedRandomList <GridPoint>(GameGen.Seed);
     for (int x = 0; x < GridPlacement.GridSize; x++)
     {
         for (int z = 0; z < GridPlacement.GridSize; z++)
         {
             //Get grid point
             GridPoint gp  = GameGen.GridPlacement.GridPoints[x, z];
             float     des = CalculateGridPointSettlementDesirability(gp);
             gp.Desirability = des;
             if (des > 0)
             {
                 DesireWeightedGridpoints.AddElement(gp, des);
             }
         }
     }
 }
예제 #40
0
    /// <summary>
    /// Creates the point. Using playing coord [1, +INF)
    /// </summary>
    /// <returns>The point.</returns>
    /// <param name="x">The x coordinate.</param>
    /// <param name="y">The y coordinate.</param>
    GridPoint CreatePoint(int x, int y)
    {
        GridPoint p =
            Instantiate(pointPrefab,
                        transform.position + new Vector3(x * unitDist, -y * unitDist, 0),
                        Quaternion.identity)
            .GetComponentInChildren <GridPoint>();

        //initialize its coordination
        p.posX = x;
        p.posY = y;

        p.transform.SetParent(pointParent);

        points.Add(p);

        return(p);
    }
        /// <summary>
        /// Initializes a new instance of the <see cref="MovementHandler"/> class.
        /// </summary>
        /// <param name="rdm">Random number generator.</param>
        /// <param name="world">The world.</param>
        public MovementHandler(Random rdm, World world)
        {
            this.random = rdm;
            this.world  = world;

            // We need to "bake" the path
            GridPoint[,] pathGrid = new GridPoint[world.Grid.Width, world.Grid.Width];
            for (int x = 0; x < world.Grid.Width; x++)
            {
                for (int y = 0; y < world.Grid.Height; y++)
                {
                    pathGrid[x, y].Cost    = world.Grid.GetSquare(x, y).GetMovementCost(rdm);
                    pathGrid[x, y].IsWater = world.Grid.GetSquare(x, y).SquareDefinition?.Definition.IsWater ?? false;
                }
            }

            this.finder = new PathFinder(pathGrid);
        }
예제 #42
0
        public static IList <GridPoint> ParseInputLines(IList <string> inputLines)
        {
            var result = new List <GridPoint>();

            for (int row = 0; row < inputLines.Count; row++)
            {
                var inputLine = inputLines[row];
                for (int column = 0; column < inputLine.Length; column++)
                {
                    if ("#".Equals(inputLine[column].ToString()))
                    {
                        var point = new GridPoint(column, row);
                        result.Add(point);
                    }
                }
            }
            return(result);
        }
예제 #43
0
        public static IList <GridPoint> GetPath(
            GridPoint startPoint,
            IList <HexMovementDirection> directions)
        {
            var result = new List <GridPoint>()
            {
                startPoint
            };
            var currentPoint = startPoint;

            foreach (var direction in directions)
            {
                var nextPoint = MoveHex(currentPoint, direction);
                result.Add(nextPoint);
                currentPoint = nextPoint;
            }
            return(result);
        }
예제 #44
0
    private void SetPath(Player player, GridPoint destPoint)
    {
        DrawWall();

        var start = new GridPoint(player.currentTile.GridPoint.X, player.currentTile.GridPoint.Y);

        var end = destPoint;

        var pathFinder = new PathFinder();

        var listPath = pathFinder.FindPath(Map.MapTiles, start, end);

        player.SetPath(listPath);

        player.OnArrivePoint = (p) => CNetworkManager.Inst.RequestPlayerMove(p.PlayerData.userId, p.currentTile.GridPoint.X, p.currentTile.GridPoint.Y, ResponseMovePlayer);

        DrawPath(listPath);
    }
예제 #45
0
        private void UpdateInvalidFieldBoundaries(GridPoint center)
        {
            BimaruValue centerValue = GetFieldValueNoCheck(center);

            foreach (Direction direction in Directions.GetAllDirections())
            {
                BimaruValue   neighbourValue = this[center.GetNextPoint(direction)];
                FieldBoundary boundary       = center.GetBoundary(direction);
                if (centerValue.IsCompatibleWith(direction, neighbourValue))
                {
                    invalidFieldBoundaries.Remove(boundary);
                }
                else
                {
                    invalidFieldBoundaries.Add(boundary);
                }
            }
        }
예제 #46
0
파일: Cluster.cs 프로젝트: herbfunk/Funky
        /// <summary>
        /// Adds point to this cluster only if it is "reachable"
        /// (if point is inside a circle of radius Dist of any cluster's points )
        /// </summary>
        /// <returns>false if point can't be added (that is either already in cluster
        /// or it is unreachable from any of the cluster's points)</returns>
        internal virtual bool AddObject(CacheObject obj)
        {
            bool l_bSuccess = true;

            if (!ContainsObject(obj) && IsPointReachable(obj.PointPosition))
            {
                ListCacheObjects.Add(obj);
                ListPoints.Add(obj.PointPosition);
                RAGUIDS.Add(obj.RAGUID);
                MidPoint += obj.PointPosition;
            }
            else
            {
                l_bSuccess = false;
            }

            return(l_bSuccess);
        }          // of AddPoint()
예제 #47
0
파일: NPC.cs 프로젝트: KianBennett/Lordship
    protected override void Update()
    {
        base.Update();

        if (wander && !Movement.HasTarget && !Movement.IsSpeaking && pauseTimer <= 0)
        {
            // Set a max distance the NPC can move to to avoid slowing down too much
            GridPoint[] roadGridPoints = TownGenerator.instance.RoadGridPoints.Where(o => Vector3.Distance(TownGenerator.instance.GridPointToWorldPos(o), transform.position) < 30).ToArray();
            GridPoint   target         = roadGridPoints[Random.Range(0, roadGridPoints.Length)];
            Movement.MoveToPoint(TownGenerator.instance.GridPointToWorldPos(target), false, false);
            bool pause = Random.value > 0.75f; // 75% chance to pause after reaching target
            pauseTimer = pause ? Random.Range(1f, 5f) : 0;
        }
        if (pauseTimer > 0)
        {
            pauseTimer -= Time.deltaTime;
        }
    }
예제 #48
0
    // returns a PathNode if this is the targetPoint
    public PathNode Visit(List <PathNode> created, Queue <PathNode> toVisit, GameObject startPoint, GameObject targetPoint, float bestCost, bool targetFound)
    {
        // if this node is the target then return this node
        if (gridPoint == targetPoint)
        {
            return(this);
        }


        // if target has been found then start pruning
        if (targetFound)
        {
            // if bestCost is less than this node cost + distace to target then prune
            if (bestCost <= cost + Vector3.Distance(gridPoint.transform.position, targetPoint.transform.position))
            {
                return(null);
            }
        }

        // check all connected gridpoints and create PathNodes or Update existing ones as neccessary
        GridPoint point = gridPoint.GetComponent <GridPoint>();

        if (point.forwardGameObject != null)
        {
            CheckNode(created, toVisit, point.forwardGameObject);
        }

        if (point.leftGameObject != null)
        {
            CheckNode(created, toVisit, point.leftGameObject);
        }

        if (point.rightGameObject != null)
        {
            CheckNode(created, toVisit, point.rightGameObject);
        }

        if (point.backGameObject != null)
        {
            CheckNode(created, toVisit, point.backGameObject);
        }

        return(null);
    }
예제 #49
0
    // Returns building that would be placed at the start of the next edge
    private Building placeBuildingsAlongEdge(Building buildingStart, Vector3 start, Vector3 end, float gapMin, float gapMax, bool leaveGapForLastBuilding = true, Bounds ignoreBounds = default)
    {
        float   edgeLength = (end - start).magnitude;
        Vector3 edgeDir    = (end - start).normalized;

        if (!buildingStart)
        {
            buildingStart = buildingPrefabs[Random.Range(0, buildingPrefabs.Length)];
        }
        Building buildingPrefabNext = buildingStart;
        Building buildingPrefab;

        // Left edge
        float dist = 0;

        while (dist < edgeLength)
        {
            buildingPrefab     = buildingPrefabNext;
            buildingPrefabNext = buildingPrefabs[Random.Range(0, buildingPrefabs.Length)];

            float length = edgeLength;
            if (leaveGapForLastBuilding)
            {
                length -= buildingPrefabNext.Size.y;
            }

            if (dist + buildingPrefab.Size.x < length)
            {
                Quaternion rot        = Quaternion.LookRotation(edgeDir, Vector3.up);
                Vector3    pos        = start + edgeDir * dist + rot * new Vector3(buildingPrefab.Size.y / 2, 0, buildingPrefab.Size.x / 2);
                GridPoint  gridPoint  = GridPointFromWorldPos(pos);
                float      noiseValue = Mathf.PerlinNoise(gridPoint.x * buildingNoiseScale, gridPoint.y * buildingNoiseScale);
                if (!ignoreBounds.Contains(pos) && noiseValue > buildingNoiseThreshold)
                {
                    Building building = Instantiate(buildingPrefab, pos, rot * Quaternion.Euler(0, 90, 0), objectContainer);
                    building.transform.localScale = MathHelper.RandomVector3(0.9f, 1.1f);
                    setGridPointsFromBuilding(building);
                }
            }
            dist += buildingPrefab.Size.x + Random.Range(gapMin, gapMax);
        }

        return(buildingPrefabNext);
    }
예제 #50
0
        public void GetFerryPathTest()
        {
            // For example:
            //
            // F10
            // N3
            // F7
            // R90
            // F11
            // These instructions would be handled as follows:
            //
            // F10 would move the ship 10 units east(because the ship starts
            // by facing east) to east 10, north 0.
            // N3 would move the ship 3 units north to east 10, north 3.
            // F7 would move the ship another 7 units east(because the ship is
            // still facing east) to east 17, north 3.
            // R90 would cause the ship to turn right by 90 degrees and face
            // south; it remains at east 17, north 3.
            // F11 would move the ship 11 units south to east 17, south 8.
            // At the end of these instructions, the ship's Manhattan distance
            // (sum of the absolute values of its east/west position and its
            // north/south position) from its starting position is 17 + 8 = 25.
            var testData = new List <Tuple <IList <string>, FerryMovementDirection, int> >()
            {
                new Tuple <IList <string>, FerryMovementDirection, int>(
                    new List <string>()
                {
                    "F10",
                    "N3",
                    "F7",
                    "R90",
                    "F11"
                }, FerryMovementDirection.East, 25)
            };

            foreach (var testExample in testData)
            {
                var instructions = FerryHelper.ParseInputLines(testExample.Item1);
                var initialState = new FerryState(GridPoint.Origin, testExample.Item2);
                var path         = FerryHelper.GetFerryPath(instructions, initialState);
                var actual       = GridPoint.GetManhattanDistance(initialState.Position, path.Last().Position);
                Assert.Equal(testExample.Item3, actual);
            }
        }
예제 #51
0
        public static GridPoint[] GeneratePath(string[] instructions)
        {
            // Initialize the path with the origin
            var currentPoint = new GridPoint();
            var path         = new List <GridPoint>(new GridPoint[] { currentPoint });

            // Generate the path by reading each instruction and moving the
            // current point to the next point as instructed
            foreach (var rawInstruction in instructions)
            {
                // The instruction should be of the following pattern:
                // 1) L/R/U/D for the direction
                // 2) A number indicating how far to move
                var instruction = rawInstruction.Trim();
                var match       = Regex.Match(instruction, "^(L|R|U|D)([0-9]+)$");
                if (!match.Success)
                {
                    throw new Exception($"Invalid instruction: {instruction}");
                }
                var direction = match.Groups[1].Value;
                var distance  = int.Parse(match.Groups[2].Value);
                for (int i = 0; i < distance; i++)
                {
                    if ("L".Equals(direction))
                    {
                        currentPoint = currentPoint.MoveLeft(1);
                    }
                    else if ("R".Equals(direction))
                    {
                        currentPoint = currentPoint.MoveRight(1);
                    }
                    else if ("U".Equals(direction))
                    {
                        currentPoint = currentPoint.MoveUp(1);
                    }
                    else if ("D".Equals(direction))
                    {
                        currentPoint = currentPoint.MoveDown(1);
                    }
                    path.Add(currentPoint);
                }
            }
            return(path.ToArray());
        }
예제 #52
0
    private void genGridPoints()
    {
        for (int i = 0; i < numCells; i++)
        {
            GridPoint gp = new GridPoint();
            gp.point     = randomPoint();
            gp.gridColor = genColor();
            gp.cost      = Vector2.Distance(gp.point, end);
            grid[i]      = gp;
        }
        // Handle the player and end points
        // They won't need a random point
        GridPoint playerPoint = new GridPoint();
        GridPoint endPoint    = new GridPoint();


        playerPoint.point     = start;
        playerPoint.gridColor = genColor();
        playerPoint.cost      = Vector2.Distance(start, end);
        grid [numCells]       = playerPoint;

        endPoint.point      = end;
        endPoint.gridColor  = genColor();
        endPoint.cost       = 0f;
        grid [numCells + 1] = endPoint;

        for (int i = 0; i < fireStart.Length; i++)
        {
            GridPoint firePoint = new GridPoint();
            firePoint.point         = fireStart[i];
            firePoint.gridColor     = genColor();
            firePoint.cost          = Vector2.Distance(start, end);
            grid [numCells + 2 + i] = firePoint;
        }

        for (int i = 0; i < miscPaths.Length; i++)
        {
            GridPoint misc = new GridPoint();
            misc.point     = miscPaths[i];
            misc.gridColor = genColor();
            misc.cost      = Vector2.Distance(start, end);
            grid [numCells + 2 + i + fireStart.Length] = misc;
        }
    }
예제 #53
0
    private void GenerateTrap()
    {
        GridPoint Switch;
        GridPoint Trap;

        do
        {
            Switch = new GridPoint(UnityEngine.Random.Range(0, GridSize / 2), UnityEngine.Random.Range(0, GridSize));
        }while (Contains(RoutePoints, Switch.y, Switch.x));
        RoutePoints.Sort((x, y) => x.y.CompareTo(y.y));
        int Countdown = 0;

        do
        {
            Trap = RoutePoints[RoutePoints.Count - 1 - Countdown];
            Countdown++;
            //Trap = new GridPoint(UnityEngine.Random.Range(GridSize / 2 + 1, GridSize), UnityEngine.Random.Range(0, GridSize));
        }while ((BorderCount(Trap.y, Trap.x) != 3));
        foreach (GridPoint t in RoutePoints)
        {
            if (t.y == Switch.y)
            {
                Route(Switch, t);
                break;
            }
        }
        Grid[Trap.y, Trap.x].transform.position = Grid[Trap.y, Trap.x].transform.position + new Vector3(0, -5, 0);
        var bc = Grid[Switch.y, Switch.x];

        bc.GetComponent <Renderer>().material.color = mycolorR;
        var trapComponent = bc.AddComponent <Trigger>();

        trapComponent.Trap = Grid[Trap.y, Trap.x];
        trapComponent.clip = gameObject.GetComponent <Sounds>().floorMoveSound;
        trapComponent.dust = gameObject.GetComponent <Effects>().dust;

        //var triggergo = new GameObject();
        //triggergo.AddComponent<BoxCollider>().isTrigger = true;
        //var tc = triggergo.AddComponent<Trigger>();
        //tc.Trap = Grid[Trap.y, Trap.x];
        //triggergo.transform.parent = bc.transform;
        //triggergo.transform.localPosition = new Vector3(0, 1, 0);
    }
예제 #54
0
        public void FieldValueChanged(IGame game, FieldValueChangedEventArgs <BimaruValue> e)
        {
            BimaruValue newValue = game.Grid[e.Point];

            foreach (Direction direction in Directions.GetAllDirections())
            {
                BimaruValueConstraint constraintInDirection = newValue.GetConstraint(direction);

                GridPoint   pointInDirection = e.Point.GetNextPoint(direction);
                BimaruValue valueInDirection = game.Grid[pointInDirection];

                // Skip set if constraint already satisfied
                if (!constraintInDirection.IsSatisfiedBy(valueInDirection))
                {
                    BimaruValue valueToSet = constraintInDirection.GetRepresentativeValue();
                    game.Grid[pointInDirection] = valueToSet;
                }
            }
        }
예제 #55
0
		public void DoTick() {
			if(pathIt == null || pathIt.MoveNext() == false) {
				if(target != null) {
					village.Destroy(target);
				}
				pathIt = CalculatePath();
				if (pathIt != null) {
					pathIt.MoveNext();
				}
			}

			if(pathIt != null) {
				this.aqPoint = pathIt.Current;
			}

			// 最短の3つの施設のうちもっとも近い施設から攻撃可能か調べ、攻撃可能な施設をタゲる
			// たぶん:ただし最短3施設がどれも移動可能エリアの場合、もっとも近い施設をタゲる
			// タゲったあとはもっとも近い射撃可能位置を探索(たぶん。距離が長すぎると打ち切り最短の壁をタゲ)
		}
        public static IMovementBehavior SpawnBehavior(UnitMoverType moverType, int speed, GridPoint spawnPos = null)
        {
            IMovementBehavior movementBehavior;
            switch (moverType)
            {
                case UnitMoverType.Flyer:
                    movementBehavior = new GenericMovementBehavior(speed, UnitMoverType.Flyer, spawnPos);
                    break;
                case UnitMoverType.Walker:
                    movementBehavior = new GenericMovementBehavior(speed, UnitMoverType.Walker, spawnPos);
                    break;
                case UnitMoverType.NoMovement:
                    movementBehavior = new NoMovementBehavior(spawnPos);
                    break;
                default:
                    movementBehavior = new GenericMovementBehavior(speed, UnitMoverType.Walker, spawnPos);
                    break;
            }

            return movementBehavior;
        }
예제 #57
0
        public static IEnumerable<GridPoint> GetPointsOnLine(GridPoint from, GridPoint to)
        {
            var x0 = from.X;
            var x1 = to.X;
            var y0 = from.Y;
            var y1 = to.Y;

            var steep = Math.Abs(y1 - y0) > Math.Abs(x1 - x0);
            if (steep)
            {
                var t = x0;
                x0 = y0;
                y0 = t;
                t = x1; // swap x1 and y1
                x1 = y1;
                y1 = t;
            }
            if (x0 > x1)
            {
                var t = x0;
                x0 = x1;
                x1 = t;
                t = y0; // swap y0 and y1
                y0 = y1;
                y1 = t;
            }
            var dx = x1 - x0;
            var dy = Math.Abs(y1 - y0);
            var error = dx / 2;
            var ystep = (y0 < y1) ? 1 : -1;
            var y = y0;
            for (var x = x0; x <= x1; x++)
            {
                yield return new GridPoint((steep ? y : x), (steep ? x : y));
                error = error - dy;
                if (error >= 0) continue;
                y += ystep;
                error += dx;
            }
        }
예제 #58
0
        private static IEnumerable<GridIndex> GetLineGridIndex(GridPoint startPositioning, GridPoint endPositioning)
        {
            //  一次函数公式: kx + b = y
            var k = (startPositioning.Y - endPositioning.Y) / (startPositioning.X - endPositioning.X);
            var b = startPositioning.Y - k * startPositioning.X;

            if (!double.IsInfinity(k))
            {
                var maxColumn = (int)Math.Floor(Math.Max(startPositioning.X, endPositioning.X) / GridConfig.Level4XCellSpan);
                var minColumn = (int)Math.Ceiling(Math.Min(startPositioning.X, endPositioning.X) / GridConfig.Level4XCellSpan);
                for (int column = minColumn; column <= maxColumn; column++)
                {
                    // 多加 1/2 的值是为了 避免 刚好在边界点因为小数点误差而计算错误
                    var x = (column + 0.00001d) * GridConfig.Level4XCellSpan;
                    var y = k * x + b;
                    yield return GetPointGridIndex(new GridPoint(x, y));
                    yield return GetPointGridIndex(new GridPoint(x - GridConfig.Level4XCellSpan, y));
                }
            }

            if (k != 0)
            {
                var maxRow = (int)Math.Floor((Math.Max(startPositioning.Y, endPositioning.Y) / GridConfig.Level4YCellSpan));
                var minRow = (int)Math.Ceiling(Math.Min(startPositioning.Y, endPositioning.Y) / GridConfig.Level4YCellSpan);
                var isInfinity = double.IsInfinity(k);

                for (int row = minRow; row <= maxRow; row++)
                {
                    // 多加 1/2 的值是为了 避免 刚好在边界点因为小数点误差而计算错误
                    var y = (row + 0.00001d) * GridConfig.Level4YCellSpan;
                    var x = isInfinity ? endPositioning.X : ((y - b) / k);
                    yield return GetPointGridIndex(new GridPoint(x, y));
                    yield return GetPointGridIndex(new GridPoint(x, y - GridConfig.Level4YCellSpan));
                }
            }
            yield return GetPointGridIndex(startPositioning);
            yield return GetPointGridIndex(endPositioning);
        }
예제 #59
0
 // The Interior Implementation
 public void FindMTPath(object x)
 {
     if(mGrid == null){
         int l = gridScript.grids[gridI].grid.Length;
         mGrid = new GridPoint[l];
         for(int z = 0; z < mGrid.Length; z++){
             mGrid[z] = new GridPoint(gridScript.grids[gridI].grid[z]);
         }
     }
     else if(mGrid.Length == 0){
         int l = gridScript.grids[gridI].grid.Length;
         mGrid = new GridPoint[l];
         for(int z = 0; z < mGrid.Length; z++){
             mGrid[z] = new GridPoint(gridScript.grids[gridI].grid[z]);
         }
     }
     if(generate){
         UPath mp = new UPath();
         mp = FindPath(end, start);
         myPath = mp;
         generate = false;
     }
 }
예제 #60
0
 public AreaBoundary(GridPoint Center)
 {
     tl=Center;
     br=Center;
 }