Skip to content

Instantly share code, notes, and snippets.

@vanaur
Created August 29, 2024 18:59
Show Gist options
  • Select an option

  • Save vanaur/14353e59c5a56b84020a7636228e6bff to your computer and use it in GitHub Desktop.

Select an option

Save vanaur/14353e59c5a56b84020a7636228e6bff to your computer and use it in GitHub Desktop.
jeu de la vie
type Grid2D<'T>(width: int, height: int, initialValue: 'T) =
let mutable grid = Array2D.init width height (fun _ _ -> initialValue)
member this.Width = width
member this.Height = height
member this.Item
with get(x, y) = grid.[x, y]
and set(x, y) value = grid.[x, y] <- value
member this.GetNeighbors(x: int, y: int): seq<'T> =
let deltas = [ -1, -1; -1, 0; -1, 1; 0, -1; 0, 1; 1, -1; 1, 0; 1, 1 ]
seq {
for dx, dy in deltas do
let nx, ny = x + dx, y + dy
if nx >= 0 && ny >= 0 && nx < this.Width && ny < this.Height then
yield grid.[nx, ny]
}
member this.ApplyRule(rule: Grid2D<'T> -> int -> int -> 'T) =
let newGrid = Array2D.init width height (rule this)
grid <- newGrid
member this.Next(rule: Grid2D<'T> -> int -> int -> 'T) =
this.ApplyRule(rule)
member this.PrintWith (fmt: 'T -> string) =
for y in 0 .. height - 1 do
for x in 0 .. width - 1 do
printf "%s" (fmt this.[x, y])
printfn ""
// Compte les voisins satisfaisant une condition donnée
let countNeighborsBy (grid: Grid2D<'T>) (predicate: 'T -> bool) (x: int) (y: int) =
grid.GetNeighbors(x, y) |> Seq.filter predicate |> Seq.length
// Règle du jeu de la vie
let gameOfLifeRule (grid: Grid2D<int>) x y =
let liveNeighbors = countNeighborsBy grid (( = ) 1) x y
match grid.[x, y], liveNeighbors with
| 1, 2 -> 1 // Survie
| 1, 3 -> 1 // Survie
| 1, _ -> 0 // Meurt par isolement ou surpopulation
| 0, 3 -> 1 // Naissance
| _ -> 0 // Reste morte
let grid = Grid2D<int>(60, 60, 0)
let rnd = System.Random()
for i in 0 .. grid.Width - 1 do
for j in 0.. grid.Height - 1 do
grid.[i, j] <- rnd.Next(0, 2)
while true do
System.Console.Clear()
grid.PrintWith (fun cell -> if cell = 0 then "██" else "░░")
grid.Next gameOfLifeRule
System.Threading.Thread.Sleep(10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment