14/02: Game of Life.
#light
open System
open Array
let width, height = 100, 100
let tick game =
let number index =
let X, Y = index % width, index / width
[|(-1, -1); (0, -1); (1, -1); (1, 0); (1, 1); (0, 1); (-1, 1); (-1, 0)|]
|> map (fun (x, y) -> X + x, Y + y)
|> filter (fun (x, y) -> x > 0 && x < width && y > 0 && y < height)
|> map (fun (x, y) -> y * width + x)
|> map (fun i -> if game.[i] then 1 else 0)
|> sum
game |> mapi (fun i alive ->
match (alive, number i) with
| (true, n) when n < 2 -> false
| (true, n) when n > 3 -> false
| (true, _) -> true
| (false, 3) -> true
| (false, _) -> false
| _ -> failwith "no."
)
let random = Random()
let mutable life = [|0..width * height - 1|] |> map (fun _ -> random.Next() % 2 = 0)
open SdlSimple
SdlSimpleSetup (width * 2) (height * 2 + 10) 16 false
draw {
let yellow = colour 255 255 0
life |> zip [|0..width * height - 1|] |> filter (fun (_, a) -> a)
|> iter (fun (i, _) -> pixel yellow (i % width * 2, i / width * 2 + 10))
life <- tick life
}
//press 'enter' to restart game.
onevent (KeyDown 13) { life <- [|0..width * height - 1|] |> map (fun _ -> random.Next() % 2 = 0) }
Console.ReadLine() |> ignore
open System
open Array
let width, height = 100, 100
let tick game =
let number index =
let X, Y = index % width, index / width
[|(-1, -1); (0, -1); (1, -1); (1, 0); (1, 1); (0, 1); (-1, 1); (-1, 0)|]
|> map (fun (x, y) -> X + x, Y + y)
|> filter (fun (x, y) -> x > 0 && x < width && y > 0 && y < height)
|> map (fun (x, y) -> y * width + x)
|> map (fun i -> if game.[i] then 1 else 0)
|> sum
game |> mapi (fun i alive ->
match (alive, number i) with
| (true, n) when n < 2 -> false
| (true, n) when n > 3 -> false
| (true, _) -> true
| (false, 3) -> true
| (false, _) -> false
| _ -> failwith "no."
)
let random = Random()
let mutable life = [|0..width * height - 1|] |> map (fun _ -> random.Next() % 2 = 0)
open SdlSimple
SdlSimpleSetup (width * 2) (height * 2 + 10) 16 false
draw {
let yellow = colour 255 255 0
life |> zip [|0..width * height - 1|] |> filter (fun (_, a) -> a)
|> iter (fun (i, _) -> pixel yellow (i % width * 2, i / width * 2 + 10))
life <- tick life
}
//press 'enter' to restart game.
onevent (KeyDown 13) { life <- [|0..width * height - 1|] |> map (fun _ -> random.Next() % 2 = 0) }
Console.ReadLine() |> ignore
next: Compiling Game of Life