Created
November 10, 2014 18:35
-
-
Save philcleveland/351147feee1bee4c0707 to your computer and use it in GitHub Desktop.
Game of life in F#
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
open System | |
open System.Threading | |
let printBoard (grid:int[,]) = | |
let maxX = (Array2D.length1 grid) - 1 | |
let maxY = (Array2D.length2 grid) - 1 | |
for row in 0 .. maxX do | |
for col in 0 .. maxY do | |
if(grid.[row,col] = 1) then printf "*|" else printf " |" | |
printfn "" | |
let tick oldBoard = | |
let width = (Array2D.length1 oldBoard) - 1 | |
let height = (Array2D.length2 oldBoard) - 1 | |
oldBoard |> | |
Array2D.mapi (fun x y cell -> | |
let xMin = if(x-1 < 0) then width - 1 else x-1 | |
let xMax = if(x+1 > width - 1) then 0 else x+1 | |
let yMin = if(y-1 < 0) then height - 1 else y-1 | |
let yMax = if(y+1 > height - 1) then 0 else y+1 | |
let v1 = oldBoard.[xMin, yMin] | |
let v2 = oldBoard.[x, yMin] | |
let v3 = oldBoard.[xMax, yMin] | |
let v4 = oldBoard.[xMin, y] | |
let v5 = oldBoard.[xMax, y] | |
let v6 = oldBoard.[xMin, yMax] | |
let v7 = oldBoard.[x, yMax] | |
let v8 = oldBoard.[xMax,yMax] | |
if(cell = 1) then | |
if(v1+v2+v3+v4+v5+v6+v7+v8 < 2 || v1+v2+v3+v4+v5+v6+v7+v8 > 3) then 0 else 1 | |
else | |
if(v1+v2+v3+v4+v5+v6+v7+v8 = 3) then 1 else 0 | |
) | |
[<EntryPoint>] | |
let main argv = | |
let rng = new System.Random((int)System.DateTime.UtcNow.Ticks) | |
let width = 25 | |
let height = 25 | |
let mutable board = Array2D.init width height (fun _ _ -> if(rng.NextDouble() > 0.5) then 1 else 0) | |
let mutable continueLooping = true | |
while continueLooping do | |
Console.Clear() |> ignore | |
printBoard board | |
board <- tick board | |
Thread.Sleep(250) | |
if(Console.KeyAvailable) then | |
let cki = Console.ReadKey(true) | |
if(cki.Key = ConsoleKey.Escape) then continueLooping <- false | |
printfn "COMPLETE" | |
Console.ReadLine() |> ignore | |
0 // return an integer exit code |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment