-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcgol.exs
More file actions
executable file
·61 lines (53 loc) · 1.34 KB
/
cgol.exs
File metadata and controls
executable file
·61 lines (53 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#!/usr/bin/env elixir
defmodule GameOfLife do
@width 50
@height 30
@density 0.2
def init_grid do
for _ <- 1..@height do
for _ <- 1..@width, do: (:rand.uniform() < @density)
end
end
def count_neighbors(grid, x, y) do
for dx <- [-1, 0, 1],
dy <- [-1, 0, 1],
not (dx == 0 and dy == 0) do
nx = rem(x + dx + @width, @width)
ny = rem(y + dy + @height, @height)
if Enum.at(Enum.at(grid, ny), nx), do: 1, else: 0
end
|> Enum.sum()
end
def next_generation(grid) do
for y <- 0..(@height - 1) do
for x <- 0..(@width - 1) do
alive = Enum.at(Enum.at(grid, y), x)
neighbors = count_neighbors(grid, x, y)
cond do
alive and (neighbors == 2 or neighbors == 3) -> true
(not alive) and neighbors == 3 -> true
true -> false
end
end
end
end
def print_grid(grid) do
# Clear screen using ANSI escape codes
IO.write("\e[H\e[2J")
Enum.each(grid, fn row ->
row_str = row |> Enum.map(fn cell -> if cell, do: "█", else: " " end) |> Enum.join("")
IO.puts(row_str)
end)
end
def loop(grid) do
print_grid(grid)
:timer.sleep(100)
loop(next_generation(grid))
end
def start do
:rand.seed(:exsplus, :os.timestamp())
grid = init_grid()
loop(grid)
end
end
GameOfLife.start()