Created
January 22, 2014 04:38
-
-
Save droyad/8553563 to your computer and use it in GitHub Desktop.
Array based Game of Life
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
| let initField x y s = | |
| match (x,y) with | |
| | (1,1) | (1, 2) | (1,3) -> true | |
| | _ -> false | |
| let valueAt (f:bool[,]) c = | |
| match c with | |
| | (x,y) when x < 0 -> false | |
| | (x,y) when y < 0 -> false | |
| | (x,y) when x >= Array2D.length1 f -> false | |
| | (x,y) when y >= Array2D.length2 f -> false | |
| | (x,y) -> f.[x,y] | |
| let rec countTrue b = | |
| match b with | |
| | true :: tail -> 1 + (countTrue tail) | |
| | false :: tail -> countTrue tail | |
| | [] -> 0 | |
| let getNeighbours f (x,y) = [ | |
| (valueAt f (x-1,y-1)) ; (valueAt f (x,y-1)); (valueAt f (x+1,y-1)) | |
| (valueAt f (x-1,y)) ; (valueAt f (x+1,y)) | |
| (valueAt f (x-1,y+1)) ; (valueAt f (x,y+1)); (valueAt f (x+1,y+1)) | |
| ] | |
| let aliveNeighbours f (x,y) = countTrue (getNeighbours f (x,y)) | |
| let newState cur neigh = | |
| match (cur, neigh) with | |
| | (_, 3) -> true | |
| | (true, 2) -> true | |
| | _ -> false | |
| let playGod f s (x, y) = newState s (aliveNeighbours f (x,y)) | |
| let tick f:bool[,] = Array2D.mapi (fun x y s -> playGod f s (x,y)) f | |
| let boolToChar b = | |
| match b with | |
| | true -> '#' | |
| | false -> ' ' | |
| let print f = Array2D.map boolToChar f | |
| let blank:bool[,] = Array2D.zeroCreate 10 10 | |
| let field0 = Array2D.mapi initField blank | |
| let field1 = tick field0 | |
| let field2 = tick field1 | |
| printfn "%A" (print field0) | |
| printfn "%A" (print field1) | |
| printfn "%A" (print field2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment