-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcgol.nim
More file actions
executable file
·56 lines (48 loc) · 1.26 KB
/
cgol.nim
File metadata and controls
executable file
·56 lines (48 loc) · 1.26 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
#!/usr/bin/env nim r
import os, times, random
const
width = 50
height = 30
density = 0.2
type
Grid = array[height, array[width, bool]]
proc initGrid(): Grid =
var grid: Grid
for y in 0..<height:
for x in 0..<width:
grid[y][x] = rand(1.0) < density
return grid
proc countNeighbors(grid: Grid, x, y: int): int =
var count = 0
for dx in -1..1:
for dy in -1..1:
if dx == 0 and dy == 0: continue
let nx = (x + dx + width) mod width
let ny = (y + dy + height) mod height
if grid[ny][nx]:
inc(count)
return count
proc nextGeneration(grid: Grid): Grid =
var newGrid: Grid
for y in 0..<height:
for x in 0..<width:
let alive = grid[y][x]
let neighbors = countNeighbors(grid, x, y)
newGrid[y][x] = (alive and (neighbors == 2 or neighbors == 3)) or
((not alive) and (neighbors == 3))
return newGrid
proc printGrid(grid: Grid) =
stdout.write("\x1B[H\x1B[2J")
for row in grid:
for cell in row:
stdout.write(if cell: "█" else: " ")
stdout.write("\n")
proc gameLoop(grid: Grid) =
var current = grid
while true:
printGrid(current)
sleep(100) # 100 milliseconds
current = nextGeneration(current)
when isMainModule:
randomize()
gameLoop(initGrid())