Skip to content

Instantly share code, notes, and snippets.

@dbuduev
Created February 29, 2016 06:37
Show Gist options
  • Save dbuduev/a2428054d3079ad13774 to your computer and use it in GitHub Desktop.
Save dbuduev/a2428054d3079ad13774 to your computer and use it in GitHub Desktop.
open System
open System.Windows.Forms
open System.Drawing
let count (a: _ [,]) x y =
let m, n = a.GetLength 0, a.GetLength 1
let mutable c = 0
for x in x-1..x+1 do
for y in y-1..y+1 do
if x>=0 && x<m && y>=0 && y<n && a.[x, y] then
c <- c + 1
if a.[x, y] then c-1 else c
let rule (a: _ [,]) x y =
match a.[x, y], count a x y with
| true, (2 | 3) | false, 3 -> true
| _ -> false
let initForm liveCells =
let form = new Form()
let (dx, dy) = (5, 5)
form.Visible <- true
let timer = new Timer(Interval=200, Enabled=true)
timer.Tick.Add(fun _ -> form.Refresh())
form.Paint.Add(fun args ->
args.Graphics.Clear(Color.White)
args.Graphics.FillRectangles(new SolidBrush(Color.Blue),
liveCells () |>
Seq.map (fun (x,y) -> new Rectangle(x*dx, y*dx, dx, dy)) |>
Seq.toArray))
form.FormClosing.Add(fun _ -> timer.Dispose())
form
let initGame n m =
let rand = System.Random()
let board = Array2D.init n m (fun _ _ -> rand.Next 6 = 0) |> ref
let update () =
board := rule !board |> Array2D.init n m
let liveCells () =
update ()
seq {
for x in 0..n-1 do
for y in 0..m-1 do
if (!board).[x,y] then yield (x,y)
}
liveCells
[<EntryPoint>]
let main args =
Application.Run(initGame 50 50 |> initForm)
0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment