Esempio n. 1
0
        public void ValueChanged()
        {
            Grid = new GridPoint[Dimension, Dimension];
            int    halfDimension = (Dimension - 1) / 2;
            double step          = (double)OuterRadius / halfDimension;

            for (int y = 0; y < Dimension; y++)
            {
                for (int x = 0; x < Dimension; x++)
                {
                    Grid[y, x] = new GridPoint();
                    double xCoord       = (x - halfDimension) * step;
                    double yCoord       = (y - halfDimension) * step;
                    double radiusSquare = (xCoord * xCoord) + (yCoord * yCoord);
                    if (radiusSquare <= OuterRadius * OuterRadius)
                    {
                        Grid[y, x].InCircle = true;
                    }
                    else
                    {
                        Grid[y, x].InCircle = false;
                    }

                    double interpolatedHeight = GetHeight(xCoord, yCoord);
                    Grid[y, x].Value = interpolatedHeight;
                }
            }

            this.Refresh();
        }
Esempio n. 2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PathFinder"/> class.
        /// </summary>
        /// <param name="grid">The calculated path finding grid.</param>
        /// <param name="pathFinderOptions">Options to path finding.</param>
        public PathFinder(GridPoint[,] grid, PathFinderOptions?pathFinderOptions = null)
        {
            this.grid = grid;

            if (this.mCalcGrid == null || this.mCalcGrid.GetLength(0) != this.grid.GetLength(0) || this.mCalcGrid.GetLength(1) != this.grid.GetLength(1))
            {
                this.mCalcGrid = new PathFinderNode[this.GridX, this.GridY];
            }

            this.open = new PriorityQueue <Point>(new PointComparer(this.mCalcGrid));

            this.options = pathFinderOptions ?? new PathFinderOptions();

            this.direction = this.options.Diagonals
                    ? new sbyte[, ]
            {
                { 0, -1 },
                { 1, 0 },
                { 0, 1 },
                { -1, 0 },
                { 1, -1 },
                { 1, 1 },
                { -1, 1 },
                { -1, -1 },
            }
                    : new sbyte[, ]
            {
                { 0, -1 },
                { 1, 0 },
                { 0, 1 },
                { -1, 0 },
            };
        }
Esempio n. 3
0
    //初始化地图
    public void Init()
    {
        sr_Bg   = transform.Find("BG").GetComponent <SpriteRenderer>();
        sr_Road = transform.Find("Road").GetComponent <SpriteRenderer>();
        CalculateSize();
        monsterPathList    = new List <GridPoint.GridIndex>();
        monsterPathPosList = new List <Vector3>();
        roundInfoList      = new List <Round.RoundInfo>();
        gridPoints         = new GridPoint[xColumn, yRow];
        for (int x = 0; x < xColumn; x++)
        {
            for (int y = 0; y < yRow; y++)
            {
#if Tool
                GameObject itemGo = Instantiate(gridGo, transform.position, transform.rotation);
#endif

#if Game
                GameObject itemGo = GameController.Instance.GetGameObjectResource("Grid");
#endif
                itemGo.transform.position = CorrectPosition(new Vector3(x * gridWidth, y * gridHeight, 0));
                itemGo.transform.SetParent(transform);
                //设置格子索引
                itemGo.GetComponent <GridPoint>().SetGridIndex(x, y);
                //将当前格子加入所有格子二维数组
                gridPoints[x, y] = itemGo.GetComponent <GridPoint>();
            }
        }
    }
Esempio n. 4
0
    //初始化地图
    public void InitMapMaker()
    {
        CalculateSize();
        gridPoints  = new GridPoint[xColumn, yRaw];
        monsterPath = new List <GridPoint.GridIndex>();
        for (int x = 0; x < xColumn; x++)
        {
            for (int y = 0; y < yRaw; y++)
            {
#if Tool
                GameObject itemGo = Instantiate(GridGo, transform.position, transform.rotation);
#endif
#if Game
                GameObject itemGo = GameController.Instance.GetGameObjectResources("Grid");
#endif
                itemGo.transform.position = CorretPostion(x * gridWidth, y * gridHeight);
                itemGo.transform.SetParent(transform);
                gridPoints[x, y] = itemGo.GetComponent <GridPoint>();
                gridPoints[x, y].gridIndex.xIndex = x;
                gridPoints[x, y].gridIndex.yIndex = y;
            }
        }
        bgSR   = transform.Find("BG").GetComponent <SpriteRenderer>();
        roadSR = transform.Find("Road").GetComponent <SpriteRenderer>();
    }
Esempio n. 5
0
        public Reconnect(Diagram diagram, GraphLayer diagramLayer, GraphLayer tempLayer, Point initialPoint)
        {
            this.diagram            = diagram;
            this.diagramLayer       = diagramLayer;
            this.tempLayer          = tempLayer;
            this.graphArrowToDelete = (GraphArrow)this.tempLayer.Elements[0];

            this.initialConnector = this.graphArrowToDelete.GetConnector(initialPoint);
            if (this.initialConnector == this.graphArrowToDelete.InitConnector)
            {
                this.fixedConnector = this.graphArrowToDelete.FinalConnector;
                this.nextEnable     = true;
            }
            else
            {
                this.fixedConnector = this.graphArrowToDelete.InitConnector;
                this.nextEnable     = false;
            }

            this.graphArrowToDelete.DisableModifiers();
            this.tempLayer.Clear();

            this.tempLayer.Add(this.tempGraphArrow);
            this.tempLayer.Visible = true;
            this.tempLayer.UpdateSurface();

            //You get the obstacles to avoid by the arrow of the diagram layer
            this.gridStatus = this.diagramLayer.GetGridPoints();
        }
Esempio n. 6
0
    public void InitMapMaker()
    {
        CalculateSize();
        gridPoints  = new GridPoint[xColumn, yRow];
        monsterPath = new List <GridPoint.GridIndex>();
        for (int x = 0; x < xColumn; x++)
        {
            for (int y = 0; y < yRow; y++)
            {
#if Tool
                GameObject itemGO = Instantiate(gridGO, transform.position, transform.rotation);
#endif
                //Debug.Log(gridWidth);
#if Game
                GameObject itemGO = GameController.Instance.GetGameObjectResource("Grid");
#endif
                itemGO.transform.position = CorrectPosition(gridWidth * x, gridHeight * y);
                itemGO.transform.SetParent(transform);
                //取到格子上面的脚本组件
                gridPoints[x, y] = itemGO.GetComponent <GridPoint>();
                //把值赋给格子里面的坐标值
                gridPoints[x, y].gridIndex.xIndex = x;
                gridPoints[x, y].gridIndex.yIndex = y;
            }
        }
        //路径和背景图的渲染
        BGSR   = transform.Find("BG").GetComponent <SpriteRenderer>();
        roadSR = transform.Find("Road").GetComponent <SpriteRenderer>();
    }
    private IEnumerable <GridPoint> GetPossibleWaypoints(GridPoint[,] options, GridPoint currentPoint)
    {
        var candidates = new List <GridPoint>();
        var position   = currentPoint.AsVector2;

        for (var x = 0; x < 3; x++)
        {
            for (var z = 0; z < 3; z++)
            {
                var gx = currentPoint.gridIndex.Item1 - 1 + x;
                var gz = currentPoint.gridIndex.Item2 - 1 + z;
                if (gx < 0 || gx >= options.GetLength(0) || gz < 0 || gz > options.GetLength(1))
                {
                    continue;
                }
                var option = options[gx, gz];
                if (option.hit)
                {
                    continue;
                }
                var distance = Vector2.Distance(position, option.AsVector2);
                if (distance <= MaximumDistance)
                {
                    candidates.Add(option);
                }
            }
        }
        return(candidates.OrderBy(x => Vector2.Distance(x.AsVector2, position)));
    }
Esempio n. 8
0
 public GridPlacement(GameGenerator2 gameGen)
 {
     GameGen    = gameGen;
     GridPoints = new GridPoint[GridSize, GridSize];
     GenRan     = new GenerationRandom(gameGen.Seed);
     GPF        = new GridPathFinder(this);
 }
        public ModifyArrow(GraphLayer diagramLayer, GraphLayer tempLayer, Point initialLocation)
        {
            this.diagramLayer = diagramLayer;
            this.tempLayer    = tempLayer;
            this.graphArrow   = (GraphArrow)this.tempLayer.Elements[0];
            this.segment      = (LineSegment)this.graphArrow.GetSegment(initialLocation);
            this.graphArrow.DisableModifiers();
            this.gridStatus = this.diagramLayer.GetGridPoints();

            if (this.segment.Modifier is VerticalModifier)
            {
                this.movement = Movement.Vertical;
                this.cursor   = Cursors.VSplit;
            }
            else
            {
                this.movement = Movement.Horizontal;
                this.cursor   = Cursors.HSplit;
            }

            this.tempLayer.Clear();
            this.tempLayer.Add(this.tempGraphArrow);
            this.tempLayer.Visible = true;
            this.tempLayer.UpdateSurface();
        }
Esempio n. 10
0
    private void Awake()
    {
        // Initialize grid
        Vector3[,] grid = GridCreator.Create2DGrid(gridWidth, cellWidth, GridCreator.Axes.XZ);
        Vector3[] positionsForLineRenderer = new Vector3[gridWidth * gridWidth];
        gridPoints = new GridPoint[gridWidth, gridWidth];

        for (int i = 0; i < gridWidth; i++)
        {
            for (int j = 0; j < gridWidth; j++)
            {
                gridPoints[i, j] = new GridPoint(grid[i, j]);
                //gridPoints[i, j].targetPosition = gridPoints[i, j].position + Vector3.up * Random.Range(0f, 40f);
                positionsForLineRenderer[i * gridWidth + j] = gridPoints[i, j].position;

                //GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
                //cube.transform.parent = transform;
                //cube.transform.localPosition = gridPositions[i, j];
                //GameObject newLetter = Instantiate(letterPrefab);
                //newLetter.transform.parent = transform;
                //gridPoints[i, j].letter = newLetter;
            }
        }

        m_LineRenderer.positionCount = positionsForLineRenderer.Length;
        m_LineRenderer.SetPositions(positionsForLineRenderer);

        // Set up noise
        noiseOffset = Random.insideUnitCircle * 1000f;

        targetScale = noiseScale;

        NodeServerManager.APIReturned += ProcessWord;
    }
Esempio n. 11
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));
    }
Esempio n. 12
0
        private List <Point> GetPathPoints(GridPoint[,] gridPoints)
        {
            List <Point> locations = new List <Point>();
            // you get the arrow path
            List <GridPoint> path = GraphDiagram.GetGridPath(gridPoints, GraphDiagram.GetNearGridPoint(this.initConnector), this.initConnector.Side, GraphDiagram.GetNearGridPoint(this.next));

            locations.Add(this.initConnector.AbsCenter);
            locations.Add(path[0].Location); //one must always be kept so that the beginning and end of the arrow are created
            //If the arrow path has more than one element, it seeks to minimize the sectors
            if (path.Count != 1)
            {
                int presentX = locations[1].X;
                int presentY = locations[1].Y;
                for (int i = 2; i < path.Count; i++)
                {
                    if ((path[i].Location.X != presentX) && (path[i].Location.Y != presentY))
                    {
                        locations.Add(path[i - 1].Location);
                        presentX = path[i - 1].Location.X;
                        presentY = path[i - 1].Location.Y;
                    }
                }
                locations.Add(path[path.Count - 1].Location);
            }
            locations.Add(this.next.AbsCenter);
            return(locations);
        }
Esempio n. 13
0
        public InsertArrow(Diagram diagram, GraphLayer diagramLayer, GraphLayer tempLayer, Point initialPoint)
        {
            this.diagram      = diagram;
            this.diagramLayer = diagramLayer;
            this.tempLayer    = tempLayer;
            MenuItem miCancel = new MenuItem("Cancelar");

            miCancel.Click += new EventHandler(MiCancel_Click);
            this.menu       = new ContextMenu(new MenuItem[] { miCancel });
            //You get the starting element and the initial connector
            this.initialConnector = this.tempLayer.Elements[0].GetConnector(initialPoint);
            //Only the connector selected for that element is enabled
            this.initialConnector.Parent.EnableConnector(this.initialConnector);
            if (this.initialConnector.Parent is GraphConditional)
            {
                this.conditionalOut = ((GraphConditional)this.initialConnector.Parent).GetPredefOut(this.initialConnector);
            }
            //Add the temporary arrow
            this.tempLayer.Add(this.tempGraphArrow);
            this.tempLayer.Visible = true;
            this.tempLayer.UpdateSurface();

            //You get the obstacles to avoid by the arrow of the diagram layer
            this.gridStatus = this.diagramLayer.GetGridPoints();
        }
Esempio n. 14
0
 // 初始化地图制造者相关变量
 public void InitMapMaker()
 {
     _instance = this;       // 如果不加这一句会获取不到MapMaker的单例
     CalcGirdSize();         // 计算相关参数
     gridPoints = new GridPoint[row, column];
     for (int i = 0; i < row; i++)
     {
         for (int j = 0; j < column; j++)
         {
                     #if Tool
             GameObject itemGo = Instantiate(gridGo, transform.position, transform.rotation);
                     #endif
             // 通过工厂拿到itemGo物体
                     #if Game
             GameObject itemGo = GameController.Instance.GetGameObjectResource("Grid");
                     #endif
             itemGo.transform.localPosition = new Vector2(-mapWidth / 2 + j * gridWidth + gridWidth / 2, -mapHeight / 2 + i * gridHeight + gridHeight / 2);
             itemGo.transform.SetParent(transform);
             gridPoints[i, j] = itemGo.GetComponent <GridPoint>();
             gridPoints[i, j].gridIndex.xIndex = i;
             gridPoints[i, j].gridIndex.yIndex = j;
         }
     }
     bgSR   = transform.Find("BG").GetComponent <SpriteRenderer>();
     roadSR = transform.Find("Road").GetComponent <SpriteRenderer>();
 }
Esempio n. 15
0
        public void UpdateArrow(GridPoint[,] gridPoints)
        {
            this.segments.Clear();
            this.rectangles.Clear();
            List <Point> locations = this.GetPathPoints(gridPoints);

            CreateArrowSurface(locations);
        }
Esempio n. 16
0
        private void Awake()
        {
            roomInfo = GetComponent <RoomInformation>();

            // The extents are actaully halfExtents
            float x = roomInfo.extents.x;
            float z = roomInfo.extents.z;

            int numberOfXTiles = Mathf.CeilToInt(x / tileSize);
            int numberOfZTiles = Mathf.CeilToInt(z / tileSize);

            grid = new GridPoint[numberOfXTiles, numberOfZTiles];
            Quaternion rot      = this.transform.rotation;
            Vector3    transPos = this.transform.position;

            for (int i = 0; i < grid.GetLength(0); i++)
            {
                for (int j = 0; j < grid.GetLength(1); j++)
                {
                    grid[i, j]      = new GridPoint();
                    grid[i, j].room = this;
                    Vector3 pos = transPos + rot * new Vector3((i * tileSize) + tileSize / 2, 0, (j * tileSize) + tileSize / 2);
                    grid[i, j].center           = pos;
                    grid[i, j].adjacentPointsXY = GetAdjacentXY(i, j, grid.GetLength(0), grid.GetLength(1));
                }
            }
            entrancePoints = new Vector2Int[roomInfo.GetEntrances.Length];
            entranceIds    = new int[roomInfo.GetEntrances.Length];
            for (int i = 0; i < roomInfo.GetEntrances.Length; i++)
            {
                Vector3 entrancePos = (roomInfo.GetEntrance(i).entranceMidPoint.transform.localPosition) / tileSize;
                int     xPos        = Mathf.FloorToInt(entrancePos.x);
                if (xPos >= grid.GetLength(0))
                {
                    xPos = grid.GetLength(0) - 1;
                }
                else if (xPos < 0)
                {
                    xPos = 0;
                }

                int zPos = Mathf.FloorToInt(entrancePos.z);
                if (zPos >= grid.GetLength(1))
                {
                    zPos = grid.GetLength(1) - 1;
                }
                else if (zPos < 0)
                {
                    zPos = 0;
                }

                grid[xPos, zPos].entrance   = roomInfo.GetEntrance(i);
                grid[xPos, zPos].isEntrance = true;
                entrancePoints[i]           = new Vector2Int(xPos, zPos);
                entranceIds[i] = roomInfo.GetEntrance(i).ID;
            }
        }
Esempio n. 17
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);
        }
Esempio n. 18
0
    public void GenerateGrid(int gridSize)
    {
        GridPoints = new GridPoint[gridSize, gridSize];

        for (int y = 0; y < gridSize; y++)
        {
            for (int x = 0; x < gridSize; x++)
            {
                GridPoints[x, y] = new GridPoint(x, y, false, GridPoint.InputType.NULL);
            }
        }
    }
Esempio n. 19
0
        public static GameState CheckForWin(GridPoint[,] board, int mineCount)
        {
            int unhiddenPoints = 0;

            foreach (var point in board)
            {
                if (!point.IsHidden && !point.IsMine)
                {
                    unhiddenPoints++;
                }
            }
            return(unhiddenPoints == board.Length - mineCount ? GameState.Won : GameState.InProgress);
        }
Esempio n. 20
0
        public void Clear(BoardSettings boardSettings)
        {
            width  = boardSettings.horizontalCutAmount + 1;
            height = boardSettings.verticalCutAmount + 1;

            grid = new GridPoint[width, height];
            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    grid[x, y] = new GridPoint(0);
                }
            }
        }
Esempio n. 21
0
 public static GridPoint[,] CalculateAdjacentMineCount(this GridPoint[,] board)
 {
     foreach (var gridPoint in board)
     {
         foreach (var neighbour in gridPoint.NeighbourCoordinates)
         {
             var point = board[neighbour[0], neighbour[1]];
             if (point.IsMine)
             {
                 gridPoint.AdjacentMineCount++;
             }
         }
     }
     return(board);
 }
Esempio n. 22
0
        public GraphArrow(Connector initialConnector, Connector finalConnector, GridPoint[,] gridPoints)
        {
            //the connectors for the arrow are saved and the elements are saved
            this.initConnector = initialConnector;
            this.previous.Add(initConnector);
            this.next = finalConnector;
            //the Arrow element is created
            this.element = new Arrow();
            this.key     = "arrow";

            // the optimized route for the arrow is loaded without intermediate points

            List <Point> locations = this.GetPathPoints(gridPoints);

            //the segments that make up the arrow are created
            this.CreateArrowSurface(locations);
        }
Esempio n. 23
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);
    }
Esempio n. 24
0
        public CelestialGrid(int rows, int columns)
        {
            points  = new GridPoint[rows, columns];
            Rows    = rows;
            Columns = columns;

            for (int i = 0; i < Rows; i++)
            {
                for (int j = 0; j < Columns; j++)
                {
                    double latitude  = i * 10 - Rows / 2 * 10;
                    double longitude = j * 15;
                    points[i, j]             = new GridPoint(longitude, latitude);
                    points[i, j].RowIndex    = i;
                    points[i, j].ColumnIndex = j;
                }
            }
        }
Esempio n. 25
0
        public static GridPoint[,] AddMinesToBoard(this GridPoint[,] board, int minesToPlace)
        {
            while (minesToPlace > 0)
            {
                var random     = new Random();
                int mineXcoord = random.Next(board.GetLength(0));
                int mineYcoord = random.Next(board.GetLength(1));

                var point = board[mineXcoord, mineYcoord];

                if (!point.IsMine)
                {
                    point.IsMine = true;
                    minesToPlace--;
                }
            }
            return(board);
        }
Esempio n. 26
0
    void Awake()
    {
        //Get dem GridPoints
        GameObject[] gameObjects = GameObject.FindGameObjectsWithTag (GRIDPOINT_TAG);

        map = new GridPoint[(int)mapSize.x, (int)mapSize.y];

        foreach (GameObject g in gameObjects) {
            GridPoint gridPoint = g.GetComponent<GridPoint>();

            if(gridPoint!=null){
                map[(int)(g.transform.position.x-minCorner.x),(int)(g.transform.position.z-minCorner.y)] = gridPoint;
            }
        }

        if (Instance == null) {
            Instance =this;
        }
    }
Esempio n. 27
0
        public static GameState MineHit(GridPoint[,] board, List <string> letters, Messages messages)
        {
            foreach (var point in board)
            {
                point.IsHidden = false;
                GridPointHelper.SetDisplayCharacter(point);
            }

            DisplayBoard(board, letters);
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(messages.Lose);
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine(messages.PlayAgain);
            Console.ForegroundColor = ConsoleColor.Gray;
            Console.WriteLine();
            return(GameState.Lost);
        }
Esempio n. 28
0
        static void executePartOne(Tuple <GridPoint[, ], List <Cart> > result)
        {
            GridPoint[,] grid = result.Item1;
            List <Cart> carts = result.Item2;

            Cart crashedCart = null;

            while (true)
            {
                if (crashedCart != null)
                {
                    break;
                }

                carts = carts.OrderBy(x => x.Y).ThenBy(x => x.X).ToList();

                foreach (Cart cart in carts)
                {
                    if (cart.Crashed)
                    {
                        continue;
                    }

                    DoMove(grid, cart);

                    Cart otherCart = carts.SingleOrDefault(x => x != cart && !x.Crashed && x.X == cart.X && x.Y == cart.Y);

                    if (otherCart != null)
                    {
                        cart.Crashed = true;

                        otherCart.Crashed = true;

                        crashedCart = cart;

                        break;
                    }
                }
            }

            Console.WriteLine("Crashed cart: " + crashedCart.X + ", " + crashedCart.Y);
        }
Esempio n. 29
0
    private void findPathAsync(GridPoint[,] gridPoints, Vector3 start, Vector3 destination, bool showMarker)
    {
        searchingForPath = true;

        GridPoint gridPointStart = TownGenerator.instance.GridPointFromWorldPos(start);
        GridPoint gridPointEnd   = TownGenerator.instance.GridPointFromWorldPos(destination);

        // If already finding a path then stop it and find a new one to avoid overlapping
        if (findPathCoroutine != null)
        {
            StopCoroutine(findPathCoroutine);
        }
        findPathCoroutine = StartCoroutine(
            Pathfinder.instance.FindPath(gridPoints, gridPointStart, gridPointEnd, debugLogMessages,
                                         delegate(List <GridPoint> points)
        {
            onPathComplete(start, destination, points, showMarker);
        })
            );
    }
Esempio n. 30
0
 private void UpdateExternalArrows()
 {
     GridPoint[,] gridPoints = this.diagramLayer.GetGridPoints();
     foreach (GraphElement element in this.tempLayer.Elements)
     {
         if (element is GraphConditional)
         {
             if ((((GraphConditional)element).NextTrue != null) && (!this.tempLayer.Elements.Contains(((GraphConditional)element).NextTrue)))
             {
                 this.externalArrows.Add((GraphArrow)((GraphConditional)element).NextTrue, ((GraphArrow)((GraphConditional)element).NextTrue).Locations);
                 ((GraphArrow)((GraphConditional)element).NextTrue).UpdateArrow(gridPoints);
             }
             if ((((GraphConditional)element).NextFalse != null) && (!this.tempLayer.Elements.Contains(((GraphConditional)element).NextFalse)))
             {
                 this.externalArrows.Add((GraphArrow)((GraphConditional)element).NextFalse, ((GraphArrow)((GraphConditional)element).NextFalse).Locations);
                 ((GraphArrow)((GraphConditional)element).NextFalse).UpdateArrow(gridPoints);
             }
         }
         else if ((element is GraphModule) || (element is GraphStart))
         {
             if ((element.Next != null) && (!this.tempLayer.Elements.Contains(element.Next)))
             {
                 this.externalArrows.Add((GraphArrow)element.Next, ((GraphArrow)element.Next).Locations);
                 ((GraphArrow)element.Next).UpdateArrow(gridPoints);
             }
         }
         if ((element is GraphConditional) || (element is GraphModule) || (element is GraphFinish))
         {
             foreach (GraphElement prev in element.Previous)
             {
                 if (!this.tempLayer.Elements.Contains(prev))
                 {
                     this.externalArrows.Add((GraphArrow)prev, ((GraphArrow)prev).Locations);
                     ((GraphArrow)prev).UpdateArrow(gridPoints);
                 }
             }
         }
     }
 }
Esempio n. 31
0
        public static GridPoint[,] AddGridPointsToBoard(this GridPoint[,] board)
        {
            var height = board.GetLength(0);
            var width  = board.GetLength(1);

            for (int x = 0; x < height; x++)
            {
                for (int y = 0; y < width; y++)
                {
                    board[x, y] = new GridPoint
                    {
                        NeighbourCoordinates = GridPointHelper.CalculateNeighbourCoordinates(x, y, height, width),
                        IsHidden             = true,
                        IsMine            = false,
                        AdjacentMineCount = 0
                    };
                }
                ;
            }
            ;
            return(board);
        }
Esempio n. 32
0
        private static int partOneCalculateTotalPower(GridPoint[,] grid, int gridSize, int x, int y, int power, int size)
        {
            int totalPower = power;

            if (x > 1)
            {
                // Left
                grid[x - 1, y].TotalPower += power;

                totalPower += grid[x - 1, y].Power;
            }

            if (y > 1)
            {
                if (x > 1)
                {
                    // Top left
                    grid[x - 1, y - 1].TotalPower += power;

                    totalPower += grid[x - 1, y - 1].Power;
                }

                // Top
                grid[x, y - 1].TotalPower += power;

                totalPower += grid[x, y - 1].Power;

                if (x + 1 <= gridSize)
                {
                    // Top right
                    grid[x + 1, y - 1].TotalPower += power;

                    totalPower += grid[x + 1, y - 1].Power;
                }
            }

            return(totalPower);
        }
Esempio n. 33
0
        public static void DisplayBoard(GridPoint[,] board, List <string> letters)
        {
            Console.Write("  ");
            foreach (var letter in letters)
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.Write(" " + letter);
                Console.ForegroundColor = ConsoleColor.Gray;
            }
            Console.WriteLine();

            for (int x = 0; x < board.GetLength(0); x++)
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.Write($"{x + 1}  ");
                Console.ForegroundColor = ConsoleColor.Gray;
                for (int y = 0; y < board.GetLength(1); y++)
                {
                    Console.Write(board[x, y].DisplayCharacter + " ");
                }
                Console.WriteLine();
            }
        }
Esempio n. 34
0
		private void Calculate() {
			int w = searchTarget.SizeX;
			int h = searchTarget.SizeY;
			opens = new bool[w,h];
			closed = new bool[w, h];
			parents = new GridPoint[w, h];
			fstars = new int[w,h];

			int fstar = GetHeuris(startPos);
			fstars[startPos.X,startPos.Y] = fstar;
			sortedOpens.Add(fstar, startPos);
			opens[startPos.X,startPos.Y] = true;
			GridPoint n;
			while (sortedOpens.PopLowest(out fstar, out n)) {
				int x = n.X;
				int y = n.Y;
				opens[x,y] = false;
				closed[x,y] = true;
				if (n.Equals(goalPos)) {
					CreatePath(n);
					pathCost = fstar;
					break;
				}
				int gstar = fstar - GetHeuris(n);

				if (y != 0) {
					if (x != 0) {
						Walk(x-1,y-1, n, 7, gstar);
					}
					Walk(x,y-1, n, 5, gstar);
					if (x != w - 1) {
						Walk(x+1,y-1, n, 7, gstar);
					}
				}
				if (x != 0) {
					Walk(x - 1,y, n, 5, gstar);
				}
				if (x != w - 1) {
					Walk(x + 1,y, n, 5, gstar);
				}
				if (y != h - 1) {
					if (x != 0) {
						Walk(x-1, y +1, n, 7, gstar);
					}
					Walk(x,y+1, n, 5, gstar);
					if (x != w - 1) {
						Walk(x+1,y+1, n, 7, gstar);
					}
				}
			}

			opens = null;
			closed = null;

			//if (path == null) {
			//	new Map(fstars, walkCostMap.Width, walkCostMap.Height).Dump("fstar.csv");
			//	new Map(parents, walkCostMap.Width, walkCostMap.Height).Dump("parents.csv");
			//	Map m = new Map(walkCostMap.Width, walkCostMap.Height);
			//	for (int i = 0; i < m.Height; i++) {
			//		for (int j = 0; j < m.Width; j++) {
			//			m[m.GetPosFromXY(j, i)] = m.GetPosFromXY(j, i);
			//		}
			//	}
			//	m.Dump("pos.csv");
			//	Debug.Log("##### route not found #### goal:"+goalPos+" start:"+startPos);
			//}
		}