示例#1
0
        public void TwoRooms()
        {
            var bountry = Bitmap.Create(new[]
            {
                "#########",
                "#  ######",
                "#  ###  #",
                "######  #",
                "#########"
            }, x => x == ' ');

            var expected = Bitmap.Create(new[]
            {
                "#########",
                "#oo######",
                "#oo###  #",
                "######  #",
                "#########"
            }, x => x == 'O');

            var start = new VectorInt2(1, 1);

            var result = FloodFill.Fill(bountry, start);

            Assert.Equal(expected, result);
        }
示例#2
0
        private void RenderFloodFillVisualization()
        {
            var map = OceanNavigator.FromString(new string[]
            {
                "    ##  ##   ##",
                "##           ##",
                "#### ##  ##   #",
                "  ## ######   #",
                "      ### ##   ",
                " ##   ### ###  ",
                " ###  ## ####  ",
                "#######  ####  ",
                "##   ####     #",
                "       ##   ###",
                "               ",
                "               ",
                "#####    ##   #",
                "#####  ####  ##",
                "       ##    ##"
            });

            var ff = new FloodFill(map);

            var overlay = ff.GetRegion(new Location(0, 0));

            var mv = new OceanNavigatorVisualizer(map);

            pictureBox2.Image = mv.Render(overlay);
        }
示例#3
0
        public void FloodFillTestMethod()
        {
            FloodFill floodFill = new FloodFill();

            int[,] result = new int[, ] {
                { 2, 2, 2 }, { 2, 2, 0 }, { 2, 0, 1 }
            };
            for (int i = 0; i < result.GetLength(0); i++)
            {
                for (int j = 0; j < result.GetLength(1); j++)
                {
                    Assert.AreEqual(result[i, j], floodFill.FloodFillSln
                                        (new int[, ] {
                        { 1, 1, 1 }, { 1, 1, 0 }, { 1, 0, 1 }
                    }, 1, 1, 2)[i, j]);
                }
            }

            int[,] result2 = new int[, ] {
                { 0, 0, 0 }, { 0, 1, 1 }
            };
            for (int i = 0; i < result2.GetLength(0); i++)
            {
                for (int j = 0; j < result2.GetLength(1); j++)
                {
                    Assert.AreEqual(result2[i, j], floodFill.FloodFillSln
                                        (new int[, ] {
                        { 0, 0, 0 }, { 0, 1, 1 }
                    }, 1, 1, 1)[i, j]);
                }
            }
        }
示例#4
0
        public void Given_FloodFill_When_GettingRegionSize_Then_CorrectSizeReturned()
        {
            var map = OceanNavigator.FromString(new string[]
            {
                "    ##  ##   ##",
                "##           ##",
                "#### ##  ##   #",
                "  ## ######   #",
                "      ### ##   ",
                " ##   ### ###  ",
                " ###  ## ####  ",
                "#######  ####  ",
                "##   ####     #",
                "       ##   ###",
                "               ",
                "               ",
                "#####    ##   #",
                "#####  ####  ##",
                "       ##    ##"
            });

            var ff = new FloodFill(map);

            var size = ff.GetRegionSize(new Location(0, 0));

            size.Should().Be(124);

            var size2 = ff.GetRegionSize(new Location(8, 6));

            size2.Should().Be(3);
        }
    void detectHoles()
    {
        renderTexture.DiscardContents();
        RenderTexture.active = camera.GetComponent <Camera> ().targetTexture;
        camera.GetComponent <Camera> ().Render();

        texture.filterMode = FilterMode.Point;
        texture.wrapMode   = TextureWrapMode.Clamp;

        texture.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
        texture.Apply();

        for (int i = 0; i < 4; i++)
        {
            TextureScale.Half(texture);
        }


        FloodFill.Fill(texture, 0, 0);
        FloodFill.Fill(texture, texture.width - 1, 0);
        FloodFill.Fill(texture, texture.width - 1, texture.height - 1);
        FloodFill.Fill(texture, 0, texture.height - 1);

        // holes
        ConnectedComponentLabeling ccl = new ConnectedComponentLabeling();

        ccl.Process(texture, texture, false, false);
        holesPositions = ccl.holesAveragePositions;

        holesPositions.Add(new Vector2(0f, 0f));
        holesPositions.Add(new Vector2((float)texture.width, 0f));
        holesPositions.Add(new Vector2(0f, (float)texture.height));
        holesPositions.Add(new Vector2((float)texture.width, (float)texture.height));
    }
示例#6
0
        public void Given_FloodFill_When_FillingValidRegion_Then_EntireRegionIsFilled()
        {
            var map = OceanNavigator.FromString(new string[]
            {
                "    ##  ##   ##",
                "##           ##",
                "#### ##  ##   #",
                "  ## ######   #",
                "      ### ##   ",
                " ##   ### ###  ",
                " ###  ## ####  ",
                "#######  ####  ",
                "##   ####     #",
                "       ##   ###",
                "               ",
                "               ",
                "#####    ##   #",
                "#####  ####  ##",
                "       ##    ##"
            });

            var ff    = new FloodFill(map);
            var start = new Location(0, 0);

            var filled = ff.GetRegion(start);

            filled[0, 0].Should().Be(true);
            filled[3, 10].Should().Be(true);

            // Not part of the original region
            filled[8, 6].Should().Be(false);

            // Not traversable
            filled[4, 0].Should().Be(false);
        }
示例#7
0
        public void FillsIrregularArea()
        {
            var map = new int[][] {
                new int[] { 0, 0, 1, 1, 1 },
                new int[] { 1, 1, 0, 0, 1 },
                new int[] { 1, 0, 0, 0, 1 },
                new int[] { 1, 0, 0, 0, 1 },
                new int[] { 1, 0, 0, 0, 1 },
                new int[] { 1, 1, 1, 1, 1 },
                new int[] { 0, 0, 0, 0, 0 }
            };

            var f = new FloodFill((p) => {
                if (p.x >= 0 && p.x < map.Length && p.y >= 0 && p.y < map[p.x].Length)
                {
                    var matches = map[p.x][p.y] == 0;

                    if (matches)
                    {
                        map[p.x][p.y] = 2;
                    }

                    return(matches);
                }

                return(false);
            });

            var totalFilled = f.Fill(new Point(2, 1));

            Assert.AreEqual(totalFilled, 11);

            Assert.AreEqual(map[1][2], 2);
            Assert.AreEqual(map[1][3], 2);
        }
示例#8
0
 private void IntegrityCheck()
 {
     if (Application.isEditor || Debug.isDebugBuild)
     {
         var result = FloodFill.BlockIntegrityTest(dungeon);
         Debug.Assert(result, "Generated dungeon is fractured!");
     }
 }
示例#9
0
        public static void FloodFillUsingWallAndCratesInline(IBitmap wall, IBitmap crate, VectorInt2 pp, IBitmap output)
        {
            var fillConstraints = new BitmapSpan(wall.Size, stackalloc uint[wall.Height]);

            fillConstraints.SetBitwiseOR(wall, crate);

            FloodFill.Fill(fillConstraints, pp, output);
        }
示例#10
0
        public static Bitmap FloodFillUsingWallAndCrates(IBitmap wall, IBitmap crate, VectorInt2 pp)
        {
            var fillConstraints = new BitmapSpan(wall.Size, stackalloc uint[wall.Height]);

            fillConstraints.SetBitwiseOR(wall, crate);

            return(FloodFill.Fill(fillConstraints, pp));
        }
示例#11
0
        public override void MouseDown(int mx, int my, bool isRightButton)
        {
            int       x      = mx - imgOffsetX;
            int       y      = my - imgOffsetY;
            FloodFill filler = new FloodFill(Color.Red);

            filler.Fill(imageToFillOn, x, y);
        }
示例#12
0
        public void AlwaysReturnsInput()
        {
            var floodFill = new FloodFill(7);

            Assert.AreEqual(7, floodFill.GetBlockID(new BlockPosition(0, 0, 0)));
            Assert.AreEqual(7, floodFill.GetBlockID(new BlockPosition(-100, 31235, 1912)));
            Assert.AreEqual(7, floodFill.GetBlockID(new BlockPosition(129, 0, 100000)));
        }
    public override float Evaluate(Representation representation)
    {
        int texSize = 1024;

        RenderTexture renderTexture     = new RenderTexture(texSize, texSize, 0);
        RenderTexture renderTextureTemp = RenderTexture.active;

        GameObject camera = new GameObject("Camera");

        camera.transform.position = new Vector3(0, 150f, -300f);

        camera.AddComponent <Camera> ();
        camera.GetComponent <Camera> ().backgroundColor  = Color.white;
        camera.GetComponent <Camera> ().orthographic     = true;
        camera.GetComponent <Camera> ().orthographicSize = 150;
        camera.GetComponent <Camera> ().targetTexture    = renderTexture;

        camera.AddComponent <GrayscaleBinary> ();
        camera.GetComponent <GrayscaleBinary> ().shader = Shader.Find("Hidden/GrayscaleBinary");

        RenderTexture.active = renderTexture;
        camera.GetComponent <Camera> ().Render();

        Texture2D texture = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.RGB24, false);

        texture.filterMode = FilterMode.Point;
        texture.wrapMode   = TextureWrapMode.Clamp;

        texture.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
        texture.Apply();


        TextureScale.Half(texture);
        texSize /= 2;

        // texture to copy
        Texture2D tempTex = new Texture2D(texture.width, texture.height);

        tempTex.SetPixels(texture.GetPixels());

        // fill
        FloodFill.Fill(tempTex, 0, 0);
        FloodFill.Fill(tempTex, tempTex.width - 1, 0);
        FloodFill.Fill(tempTex, tempTex.width - 1, tempTex.height - 1);
        FloodFill.Fill(tempTex, 0, tempTex.height - 1);

        // holes
        ConnectedComponentLabeling ccl = new ConnectedComponentLabeling();
        int holes = ccl.Process(tempTex, texture, false);


        RenderTexture.active = renderTextureTemp;
        GameObject.DestroyImmediate(camera);

        return(holes * (1f + Mathf.Exp(2f)) / (28.4103f * Mathf.Exp(2f)) + 43.9867f / 28.4103f);
    }
        private static void WalkTheDungeon(Game gameInstance)
        {
            Logger.Info("Walking the dungeon...");

            var pathFinder      = new AStarPathFinding();
            var movementProfile = new HumanoidMovement();
            var visibilityMap   = new VisibilityMap(gameInstance.Terrain.Width, gameInstance.Terrain.Height, null, null);

            var walkableLocations = gameInstance.Terrain.WalkableLocations(movementProfile).ToList();

            FloodFill.Fill(gameInstance.Terrain, visibilityMap, movementProfile, walkableLocations[Rng.Next(walkableLocations.Count - 1)]);

            var walkableUnseenLocations = GetWalkableUnseenLocations(gameInstance.Terrain, visibilityMap, movementProfile).ToList();

            while (walkableUnseenLocations.Count > 0)
            {
                var closestExploredLocation   = GetClosestExploredLocation(gameInstance.Terrain, visibilityMap, movementProfile, walkableUnseenLocations[Rng.Next(walkableUnseenLocations.Count - 1)]);
                var closestUnexploredLocation = GetClosestUnexploredLocation(gameInstance.Terrain, visibilityMap, movementProfile, closestExploredLocation.Value);

                var movementPath = pathFinder.FindPath(gameInstance.Terrain, new List <IActor>(), new DiggerMovement(), closestExploredLocation.Value, closestUnexploredLocation.Value);
                foreach (var node in movementPath)
                {
                    gameInstance.Terrain[node.Location]  = new Floor();
                    visibilityMap[node.Location].WasSeen = true;
                }

                visibilityMap[closestUnexploredLocation.Value].WasSeen = false;
                FloodFill.Fill(gameInstance.Terrain, visibilityMap, movementProfile, closestUnexploredLocation.Value);

                walkableUnseenLocations = GetWalkableUnseenLocations(gameInstance.Terrain, visibilityMap, movementProfile).ToList();
            }


            //digger.VisibilityMap.UpdateVisibilityMap(gameInstance.Terrain, gameInstance.LightMap, digger.Location.Coordinate);
            //var command = digger.Intellect.GetNextAction();
            //while (command is MoveCommand)
            //{
            //    var result = command.Execute();
            //    if ((!result.Success) && (command is MoveCommand))
            //    {
            //        // The move action failed
            //        // Ask the actor for a default action on bump
            //        var defaultBumpAction = digger.Intellect.GetDefaultBumpAction((MoveCommand)command);
            //        if (defaultBumpAction != null)
            //           defaultBumpAction.Execute();
            //    }

            //    digger.VisibilityMap.UpdateVisibilityMap(gameInstance.Terrain, gameInstance.LightMap, digger.Location.Coordinate);
            //    command = digger.Intellect.GetNextAction();
            //}

            //gameInstance.RemoveActor(digger);
            Logger.Info("Dungeon walk complete.");
        }
示例#15
0
 void InternalTest(int[][] image, int sr, int sc, int newColor, int[][] expected)
 {
     int[][] actual = FloodFill.Solve(image, sr, sc, newColor);
     Assert.Equal <int>(expected.GetLength(0), actual.GetLength(0));
     for (int i = 0; i < image.GetLength(0); i++)
     {
         for (int j = 0; j < image[i].GetLength(0); j++)
         {
             Assert.Equal <int>(expected[i][j], actual[i][j]);
         }
     }
 }
示例#16
0
        private void BeginDrawingObject(MouseButtonEventArgs e)
        {
            Vector mousePos = (Vector)e.GetPosition(MainImageContainer);

            switch (currentlyPressedButton.Name)
            {
            case "DrawLineButon":
                ILine line = new ClippedLine((Vector)e.GetPosition(MainImageContainer), (Vector)e.GetPosition(MainImageContainer), 2, CurrentColor, ClipRectangles);
                currentlyDrawnObject = line;
                DrawingObjects.Add(currentlyDrawnObject);
                currentlyDrawnPoint = line.Point2;
                break;

            case "DrawCircleButton":
                MidpointCircle circle = new MidpointCircle((Vector)e.GetPosition(MainImageContainer), (Vector)e.GetPosition(MainImageContainer), CurrentColor);
                currentlyDrawnObject = circle;
                DrawingObjects.Add(currentlyDrawnObject);
                currentlyDrawnPoint = circle.radiusUtilityPoint;
                break;

            case "DrawPolygonButton":
                Polygon poly = new FilledPolygon(CurrentColor, 2, ClipRectangles, (Vector)e.GetPosition(MainImageContainer), (Vector)e.GetPosition(MainImageContainer));
                currentlyDrawnObject = poly;
                DrawingObjects.Add(currentlyDrawnObject);
                currentlyDrawnPoint = poly.Points[1];
                break;

            case "DrawCapsuleButton":
                Capsule cap = new Capsule(mousePos, mousePos, 0, CurrentColor);
                currentlyDrawnObject = cap;
                DrawingObjects.Add(currentlyDrawnObject);
                currentlyDrawnPoint = cap.Point2;
                break;

            case "DrawRectangleButton":
                DrawingRectangle rec = new DrawingRectangle(CurrentColor, 2, mousePos, mousePos);
                currentlyDrawnObject = rec;
                DrawingObjects.Add(currentlyDrawnObject);
                currentlyDrawnPoint = rec.Points[2];
                break;

            case "FloodFillButton":
                FloodFill fill = new FloodFill(mousePos, CurrentColor);
                DrawingObjects.Add(fill);
                currentState = UIState.PreparingToDraw;
                break;

            default:
                throw new NotImplementedException();
            }
        }
示例#17
0
        public void CycleAndFill()
        {
            var map = new int[][] {
                new int[] { 0, 0, 0, 0, 0 },
                new int[] { 0, 0, 0, 0, 0 },
                new int[] { 0, 0, 1, 1, 1 },
                new int[] { 0, 0, 1, 0, 1 },
                new int[] { 1, 1, 1, 0, 1 },
                new int[] { 1, 0, 0, 0, 1 },
                new int[] { 1, 0, 0, 0, 1 },
                new int[] { 1, 1, 1, 1, 1 }
            };

            // Detect shape
            var d = new CycleDetection(new Point(4, 0), (p) => {
                if (p.x >= 0 && p.x < map.Length && p.y >= 0 && p.y < map[p.x].Length)
                {
                    return(map[p.x][p.y] == 1);
                }

                return(false);
            });

            Assert.AreEqual(d.Cycles.Count, 1);

            // Find the centroid of the triangle
            var centroid = d.Cycles[0].TriangleSample.Centroid;

            Assert.AreEqual(centroid, new Point(6, 1));

            // Flood fill the interior of the structure
            var f = new FloodFill((p) => {
                if (p.x >= 0 && p.x < map.Length && p.y >= 0 && p.y < map[p.x].Length)
                {
                    var matches = map[p.x][p.y] == 0;

                    if (matches)
                    {
                        map[p.x][p.y] = 2;
                    }

                    return(matches);
                }

                return(false);
            });

            var totalFilled = f.Fill(centroid);

            Assert.AreEqual(totalFilled, 8);
        }
示例#18
0
        public bool ShowFloodFill(bool randomize)
        {
            // find all nodes reachable from source node
            T   source    = FindSource(randomize);
            var floodFill = new FloodFill <T>(Graph);

            Predicate <T> match   = p => NodeCosts[p] <= MaxCost / 2;
            bool          success = floodFill.FindMatching(match, source);

            Locations = floodFill.Nodes;

            Renderer.InvalidateVisual();
            return(success);
        }
示例#19
0
        public SolverNodeRoot CreateRoot(Puzzle puzzle)
        {
            var crate       = puzzle.ToMap(puzzle.Definition.AllCrates);
            var moveBoundry = crate.BitwiseOR(puzzle.ToMap(puzzle.Definition.Wall));
            var move        = FloodFill.Fill(moveBoundry, puzzle.Player.Position);
            var root        = new SolverNodeRoot(
                puzzle.Player.Position, new VectorInt2(),
                crate, move,
                this,
                puzzle
                );

            return(root);
        }
示例#20
0
 public Boolean isMapAccepted()
 {
     DesignMap.printDebug();
     if (isEmpty())
     {
         Console.WriteLine("Error Can't Save Map [no object found]");
     }
     else
     {
         FloodFill ff = new FloodFill(map, height, width);
         if (ff.isFFAccepted())
         {
             return(true);
         }
     }
     return(false);
 }
    void Start()
    {
        _filler = new FloodFill();

        _layout = _generator.CreateDungeon();

        _rooms = _filler.GetAllRooms <string>(_layout, "Floor");

        _dungeon = GridBuilder.Instance.BuildGrid(_layout, transform);

        for (int i = 0; i < _rooms.Length; i++)
        {
            Color Coler = Random.ColorHSV();
            for (int j = 0; j < _rooms[i].Count; j++)
            {
                _dungeon.GetNode(_rooms[i][j]).GetComponent <MeshRenderer>().material.color = Coler;
            }
        }
    }
示例#22
0
        private Point?GetExploreDestination()
        {
            //todo, clean up later
            var potentiallyReachable = FloodFill.ScanToArray(Player.Position, point => !point.IsMapEdge() && (!Map.Seen[point] || TileDefinition.IsPassable(TileTypeAt(point))));
            var dm2 = new DijkstraMap(p => (Map.Seen[p] || p.IsMapEdge())? -1 : 1)              //todo, seen==blocked?
            {
                IsSource = p => (Map.Seen[p] || p.IsMapEdge())
            };

            dm2.Scan();
            //CharacterScreens.PrintDijkstraTest(dm2);
            foreach (Point p in Map.GetAllPoints(false))
            {
                if (dm2[p] == DijkstraMap.Unexplored || dm2[p] == DijkstraMap.Blocked)
                {
                    continue;
                }
                dm2[p] = -(dm2[p] * dm2[p]);
            }
            dm2.RescanWithCurrentValues();
            //CharacterScreens.PrintDijkstraTest(dm2);
            var dm = new DijkstraMap(p => (!Map.Seen[p] || !TileDefinition.IsPassable(TileTypeAt(p)))? -1 : 1)
            {
                IsSource       = p => !Map.Seen[p] && potentiallyReachable[p],
                GetSourceValue = p => - (dm2[p])
            };

            dm.Scan();
            //CharacterScreens.PrintDijkstraTest(dm2);
            //CharacterScreens.PrintDijkstraTest(dm);
            List <Point> playerPath = dm.GetDownhillPath(Player.Position, true, earlyStopCondition: p => !Map.Seen[p]);

            if (playerPath.Count == 0)
            {
                return(null);
            }
            else
            {
                return(playerPath[playerPath.Count - 1]);
            }
        }
示例#23
0
        public void FillsSimpleArea()
        {
            var map = new int[][] {
                new int[] { 0, 0, 0, 0, 0 },
                new int[] { 1, 1, 1, 1, 1 },
                new int[] { 1, 0, 0, 0, 1 },
                new int[] { 1, 0, 0, 0, 1 },
                new int[] { 1, 0, 0, 0, 1 },
                new int[] { 1, 1, 1, 1, 1 },
                new int[] { 0, 0, 0, 0, 0 }
            };

            var f = new FloodFill((p) => {
                if (p.x >= 0 && p.x < map.Length && p.y >= 0 && p.y < map[p.x].Length)
                {
                    var matches = map[p.x][p.y] == 0;

                    if (matches)
                    {
                        map[p.x][p.y] = 2;
                    }

                    return(matches);
                }

                return(false);
            });

            var totalFilled = f.Fill(new Point(2, 1));

            Assert.AreEqual(totalFilled, 9);

            for (var x = 2; x < 5; x++)
            {
                for (var y = 1; y < 4; y++)
                {
                    Assert.AreEqual(map[x][y], 2);
                }
            }
        }
示例#24
0
        public void CaseA()
        {
            var report = new TestReport();

            var sample = new[]
            {
                "#############",
                "#a ###    b##",
                "# A######  ##",
                "#  ######B ##",
                "#########  ##",
                "#############"
            };


            var boundry = Bitmap.Create(sample, x => x == '#');  //sample.ToMap('#', 'A', 'B');

            var staticMaps = new StaticMaps(
                Bitmap.Create(sample, '#'),
                Bitmap.Create(sample, ' ', 'a', 'b'),
                null,
                null
                );
            var stateMaps = new StateMaps(
                Bitmap.Create(sample, 'A', 'B'),
                FloodFill.Fill(staticMaps.WallMap, Bitmap.FindPosition(sample, 'a')));

            var pushMap = PushMap.Find(staticMaps, stateMaps, Bitmap.FindPosition(sample, 'A'),
                                       Bitmap.FindPosition(sample, 'b'));


            report.WriteLine(pushMap);

            Assert.Equal(new TestReport(@".............
..X..........
.............
..X..........
.............
............."), report);
        }
示例#25
0
        public void Sample()
        {
            var bountry = Bitmap.Create(new[]
            {
                "~~~###~~~~~",
                "~~## #~####",
                "~##  ###  #",
                "## X      #",
                "#    X #  #",
                "### X###  #",
                "~~#  #    #",
                "~## ## # ##",
                "~#      ##~",
                "~#     ##~~",
                "~#######~~~"
            });

            var expected = Bitmap.Create(new[]
            {
                "~~~###~~~~~",
                "~~## #~####",
                "~##  ###  #",
                "## X      #",
                "#    X #  #",
                "### X###  #",
                "~~#  #    #",
                "~## ## # ##",
                "~#      ##~",
                "~#     ##~~",
                "~#######~~~"
            }, x => x == ' ');

            var start = new VectorInt2(4, 4);


            var result = FloodFill.Fill(bountry, start);

            Assert.Equal(expected, result);
        }
示例#26
0
    private IEnumerator FillMap()
    {
        if (_isDrawing)
        {
            yield break;
        }

        _isDrawing = true;

        _fillNodes = new List <Node>();
        FloodFill.HandleAddNodeToRegion += AddToMapFill;

        FloodFill.FillMap();

        FloodFill.HandleAddNodeToRegion -= AddToMapFill;

        //600 frames
        //_fillNodes.Count / 600

        int iterationCount = _fillNodes.Count / 600;
        int i = 0;

        foreach (var n in _fillNodes)
        {
            GridCreator.Instance.ColorTileAt(n.X, n.Y, n.rColor);
            if (i > iterationCount)
            {
                yield return(null);

                i = 0;
            }
            else
            {
                i++;
            }
        }

        _isDrawing = false;
    }
示例#27
0
        private List <Point> GetPathToNearbyReachable(Point potentialDestination, DijkstraMap playerMovementMap, ref PointArray <bool> knownReachable, ref DijkstraMap distanceToKnownReachable)
        {
            Point destination = potentialDestination;

            // First, figure out whether the destination cell is known-reachable:
            if (knownReachable == null)
            {
                knownReachable = FloodFill.ScanToArray(Player.Position, CellIsKnownPassable);
            }
            PointArray <bool> knownReachable2 = knownReachable;            // Can't use a ref parameter inside a lambda, but using a 2nd variable works.

            if (!knownReachable[destination])
            {
                // If not, then find the nearest known reachable spaces:
                if (distanceToKnownReachable == null)
                {
                    distanceToKnownReachable = new DijkstraMap(point => 1)
                    {
                        IsSource = point => knownReachable2[point]
                    };
                    distanceToKnownReachable.Scan();
                }
                if (distanceToKnownReachable[destination] > 1)                                                                       // If distance is 1, then we can reach it anyway
                {
                    destination = destination.EnumeratePointsAtChebyshevDistance(distanceToKnownReachable[destination], true, false) // We know the distance already, so check only those cells...
                                  .Where(nearby => nearby.ExistsBetweenMapEdges() && knownReachable2[nearby])                        // ...make sure only reachable ones are considered...
                                  .WhereLeast(nearby => destination.GetHalfStepMetricDistance(nearby))                               // ...get the nearest ones to the targeted point...
                                  .WhereLeast(nearby => Player.Position.GetHalfStepMetricDistance(nearby))[0];                       // ...and finally get whichever one of those is closest to the player.
                }
            }
            if (destination == Player.Position)
            {
                return(new List <Point>());
            }
            List <Point> path = playerMovementMap.GetDownhillPath(destination, preferCardinalDirections: true, includePathSource: true, includePathDestination: false, ignorePathSourceCost: true);

            path.Reverse();
            return(path);
        }
示例#28
0
    static void Main(string[] args)
    {
        // Example usage:
        int length = 10, width = 10;

        bool[,] map = new bool[10, 10];
        map[2, 2]   = true;
        map[2, 3]   = true;
        map[3, 3]   = true;
        map[4, 3]   = true;
        map[4, 2]   = true;
        map[4, 1]   = true;
        map[3, 1]   = true;
        map[2, 1]   = true;
        // //Define filled/empty nodes here
        int count = FloodFill.GetSizeOfBlock(map, new Vector2(10, 10), new Vector2(2, 2));

        Console.WriteLine("Count = " + count);
        for (int i = 0; i < length; i++)
        {
            for (int j = 0; j < width - 1; j++)
            {
                Console.Write(map[i, j] + ", ");
            }
            Console.WriteLine(map[i, width - 1]);
        }
        Console.ReadKey();
        map = FloodFill.Fill(map, new Vector2(10, 10), new Vector2(0, 0));
        for (int i = 0; i < length; i++)
        {
            for (int j = 0; j < width - 1; j++)
            {
                Console.Write(map[i, j] + ", ");
            }
            Console.WriteLine(map[i, width - 1]);
        }
        Console.ReadKey();
    }
示例#29
0
        private void ChooseAutoexploreAction(PlayerTurnEvent e)
        {
            var potentiallyReachable = FloodFill.ScanToArray(Player.Position, point => !point.IsMapEdge() && (!Map.Seen[point] || TileDefinition.IsPassable(TileTypeAt(point))));
            var distanceToKnown      = new DijkstraMap(p => (Map.Seen[p] || p.IsMapEdge())? -1 : 1)
            {
                IsSource = p => (Map.Seen[p] || p.IsMapEdge())
            };

            distanceToKnown.Scan();
            foreach (Point p in Map.GetAllPoints(false))
            {
                if (distanceToKnown[p] == DijkstraMap.Unexplored || distanceToKnown[p] == DijkstraMap.Blocked)
                {
                    continue;
                }
                distanceToKnown[p] = -(distanceToKnown[p] * distanceToKnown[p]);
            }
            distanceToKnown.RescanWithCurrentValues();
            var exploreMap = new DijkstraMap(p => (!Map.Seen[p] || !TileDefinition.IsPassable(TileTypeAt(p)))? -1 : 1)              // todo, needs items, shrines, etc. eventually
            {
                IsSource       = p => !Map.Seen[p] && potentiallyReachable[p],
                GetSourceValue = p => - (distanceToKnown[p])
            };

            exploreMap.Scan();
            List <Point> playerPath = exploreMap.GetDownhillPath(Player.Position, true, earlyStopCondition: p => true);

            if (playerPath.Count == 0)
            {
                return;
            }
            else
            {
                e.ChosenAction = new WalkAction(Player, playerPath[0]);
            }
        }
        public void FloodFill(XRayImage xRayImage)
        {
            ImageHistory.Push(xRayImage.XRayBitmap);
            var originalImage = xRayImage.XRayBitmap;

            using (var bitmap = ImageUtils.BitmapImage2Bitmap(originalImage))
            {
                var floodFill = new FloodFill();
                // top & bottom borders
                for (var x = 0; x < bitmap.Width; x += 100)
                {
                    floodFill.Fill(bitmap, new System.Drawing.Point(x, 0), System.Drawing.Color.Black, System.Drawing.Color.Transparent);
                    floodFill.Fill(bitmap, new System.Drawing.Point(x, bitmap.Height - 1), System.Drawing.Color.Black, System.Drawing.Color.Transparent);
                }
                // left & right borders
                for (var y = 0; y < bitmap.Height; y += 100)
                {
                    floodFill.Fill(bitmap, new System.Drawing.Point(0, y), System.Drawing.Color.Black, System.Drawing.Color.Transparent);
                    floodFill.Fill(bitmap, new System.Drawing.Point(bitmap.Width - 1, y), System.Drawing.Color.Black, System.Drawing.Color.Transparent);
                }

                xRayImage.XRayBitmap = bitmap.Bitmap2BitmapImage();
            }
        }
        public void clearPoles(List<vector2i> wallList)
        {
            // #Clears out lonely walls, or "Poles".

            FloodFill f = new FloodFill();
            for (int x = 0; x < newDungeon.GetLength(0); x++){
                for (int y = 0; y < newDungeon.GetLength(1); y++){
                    if (newDungeon[x,y] == wall && countAdjWall (new vector2i(x,y)) == 0){
                        newDungeon [x,y] = space;
                    } else if(f.reachableSpaces(newDungeon, new vector2i(x,y)) < 10) {
                        newDungeon [x,y] = wall;
                    }
                }
            }

            //			List<vector2i> newSpaces = new List<vector2i> ();
            //			foreach (vector2i i in wallList) {
            //				if (countAdjWall (i) == 0) {
            //					newDungeon [i.x,i.y] = space;
            //					newSpaces.Add (i);
            //				}
            //			}
            //			foreach (vector2i i in newSpaces) {
            //				wallList.Remove (i);
            //			}

            //return wallList;
        }
        public List<vector2i> wallCrawl(List<vector2i> wallList)
        {
            List<vector2i> newWalls = new List<vector2i> ();
            FloodFill f = new FloodFill ();
            vector2i start = null;
            for (int x = 0; x < newDungeon.GetLength(0); x++){
                for (int y = 0; y < newDungeon.GetLength(1); y++){
                    if ( newDungeon[x,y] == space){
                        start = new vector2i (x, y);
                        break;
                    }
                }
                if (start != null){
                    break;
                }
            }
            UnityEngine.Debug.Log ("(" + start.x + " " + start.y + ")");

            foreach (vector2i i in wallList) {
                int spaces = f.reachableSpaces (newDungeon, start);
                List<vector2i> card = i.getCardinalTiles (newDungeon.GetLength(0), newDungeon.GetLength(1));
                vector2i newWall = card [rand.Next (0, card.Count)];

                if (newDungeon[newWall.x, newWall.y] == space){
                    newWalls.Add (newWall);
                    newDungeon [newWall.x,newWall.y] = wall;
                    int newSpaces = f.reachableSpaces(newDungeon, start);

                    if (spaces - newSpaces > 3){
                        newWalls.Remove (newWall);

                        newDungeon [newWall.x,newWall.y] = space;
                    } else {
                        spaces = newSpaces;
                    }

                }

            }

            wallList.AddRange (newWalls);

            //newWalls = new List<vector2i> ();

            return wallList;
        }
	public void OnMouseUp()
	{
	    grid.ResetColor();

		if (Scoring.moveLimit <= Scoring.actualMoves) {

			Stars stars = GameObject.Find ("Stars").GetComponent<Stars>();

			// one more stars => win screen
			// less than one star => losing screen
			Application.LoadLevel(stars.oneStar.isEnabled() ? (int)Prefabs.Scene.winscreen : (int)Prefabs.Scene.losingscreen);
		}

		// 0) something selected?
		if (selectedTiles.Count < 1) {
			moveToStartPosition();
			return;
		}
			

		// 1) find closest tile
        Piece closestPiece = FindNearestTile();

		// can't drop same color on same tile
		if (piece.type == closestPiece.type) {
			//Debug.Log ("dropped on same color");
			moveToStartPosition ();
			return; 
		}

		//Debug.Log ("doing some floodflill");

		// 2) swap with playerTile and set it towards start position (maybe some transition?)
		// 2.1) set player controlled tile to grid tile
		transform.position = closestPiece.gameObject.transform.position;
		// 2.2 add drag-ability to new tile
		closestPiece.gameObject.AddComponent<DragDrop> (); 
		// 2.3) change index meta info

		piece.SwapPosition (closestPiece); // not needed currently

		// move limit
		Scoring.actualMoves++;

		// update moves label
		GameObject.Find ("Moves").guiText.text = ""+(Scoring.moveLimit +1 - Scoring.actualMoves);

		//Debug.Log (closestTile.GetComponent<TileMetaData>().index);

		// 3) find matching tiles
		FloodFill floodFill = new FloodFill ();
		List<Piece> matches = floodFill.FillFromPiece(gameObject.GetComponent<Piece>(), grid);
		// gameObject.AddComponent<ExplodeNeighbours> ().Neighbours = Neighbours;

	

		// 4) make some fancy explosions
		if (matches.Count > 2) {

			int bonusValue;
			if(matches.Count >= Scoring.mediumGroupSize && matches.Count < Scoring.bigGroupSize)
			{
				bonusValue = Scoring.mediumBonus;
			}else if(matches.Count >= Scoring.bigGroupSize)
			{
				bonusValue = Scoring.bigBonus;
			}else
			{
				bonusValue = 1;
			}
			
			Scoring.setFinalScore(Scoring.finalScore + (Scoring.pieceValue * matches.Count * bonusValue));
			Debug.Log("Score earned for the match: " + Scoring.finalScore);
			Debug.Log("Final Score: " + Scoring.finalScore);


			List<int> cols = new List<int>();

			Debug.Log ("Desotryed " + matches.Count + " Pieces");
			foreach (Piece match in matches) {

				// match.AddComponent<Explode>();

				grid.SetPieceAt(null, match.x, match.y);

				if(!cols.Contains(match.x))
				   cols.Add(match.x);

				StartCoroutine(explosion(match));


				Destroy (match.gameObject);
			}

			grid.dropRows(cols);
		}

		// remove dragging script from old tile
		Destroy (this);
	}