Created
October 3, 2014 13:19
-
-
Save saevarb/1ad2823cac343222f702 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Alright, so let's say you want to 'bucket fill' at some coordinate (x,y) | |
Let's pretend that the pixels at the coordinate look like this | |
123 | |
456 | |
789 | |
That is, you have (x, y) pointing to the pixel '5' in this case. | |
Assuming that (0,0) is the top-left corner, then the pixel '1' is at | |
(x - 1, y - 1) and similarly, the pixel '9' is at (x + 1, y + 1). | |
So if you're given a coordinate (x, y) and you want to enumerate the pixels | |
around that coordinate(or rather, generate the coordinates which you then | |
use to paint the pixels afterwards) your haskell code might look something | |
like this: | |
getAdjacent (x, y) = | |
[(x', y') | x' <- [x - 1 .. x + 1], y' <- [y - 1 .. y + 1]] | |
λ: let getAdjacent (x, y) = [(x', y') | x' <- [x - 1 .. x + 1], y' <- [y - 1 .. y + 1]] | |
λ: getAdjacent (3, 3) | |
[(2,2),(2,3),(2,4),(3,2),(3,3),(3,4),(4,2),(4,3),(4,4)] | |
This is from ghci, so it works. But there are corner cases. If you ask for | |
the pixels around (0, 0), you get coordinates like (-1, -1) which aren't | |
valid. This is easy to get around, but it requires your function to know | |
about the dimensions of the picture. | |
getadjacent (x, y) dimX dimY = | |
let coords = [(x', y') | x' <- [x - 1 .. x + 1], y' <- [y - 1 .. y + 1]] | |
in filter validCoord coords | |
where | |
validCoord (i, j) = i >= 0 && i < dimX && j >= 0 && j < dimY | |
Note that this function is just an example.. I have little time so it might | |
not type check. | |
Additionally, since you're filtering colors and so on, you could add another | |
function that checks if the color is the same as color at the origin. This | |
assumes you have some way of accessing the canvas and so on, so you might | |
have to add the canvas as an argument(or use the State monad or some such). | |
getadjacent (x, y) dimX dimY canvas = | |
let coords = [(x', y') | x' <- [x - 1 .. x + 1], y' <- [y - 1 .. y + 1]] | |
in filter validCoord coords | |
where | |
validCoord (i, j) = i >= 0 && i < dimX && j >= 0 && j < dimY | |
validColor (i, j) = colorAt (i, j) canvas == colorAt (x, y) canvas | |
colorAt = -- some definition for colorAt that gets the color at a coordinate. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment