| 1 | import term |
| 2 | import rand |
| 3 | import time |
| 4 | |
| 5 | const cell = '█' |
| 6 | const nothing = ' ' |
| 7 | const transformers = [nothing, cell] |
| 8 | |
| 9 | struct Game { |
| 10 | mut: |
| 11 | grid [][]string |
| 12 | } |
| 13 | |
| 14 | fn (g Game) get_surrounding_alive_count(x int, y int) int { |
| 15 | mut count := 0 |
| 16 | for i := x - 1; i <= x + 1; i++ { |
| 17 | for j := y - 1; j <= y + 1; j++ { |
| 18 | if (i != x || j != y) && i >= 0 && j >= 0 && i < g.grid.len && j < g.grid[x].len { |
| 19 | if g.grid[i][j] == cell { |
| 20 | count++ |
| 21 | } |
| 22 | } |
| 23 | } |
| 24 | } |
| 25 | return count |
| 26 | } |
| 27 | |
| 28 | fn (mut g Game) evolve() { |
| 29 | mut temp_grid := [][]string{} |
| 30 | for x in 0 .. g.grid.len { |
| 31 | temp_grid << []string{} |
| 32 | for y in 0 .. g.grid[x].len { |
| 33 | count := g.get_surrounding_alive_count(x, y) |
| 34 | if count == 3 || (g.grid[x][y] == cell && count == 2) { |
| 35 | temp_grid[x] << cell |
| 36 | } else { |
| 37 | temp_grid[x] << nothing |
| 38 | } |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | g.grid = temp_grid |
| 43 | } |
| 44 | |
| 45 | fn (mut g Game) display() { |
| 46 | for y in 0 .. g.grid[0].len { |
| 47 | mut line := '' |
| 48 | for x in 0 .. g.grid.len { |
| 49 | line += g.grid[x][y] |
| 50 | } |
| 51 | println(line) |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | fn new_game() Game { |
| 56 | w, h := term.get_terminal_size() |
| 57 | mut grid := [][]string{} |
| 58 | for x in 0 .. w { |
| 59 | grid << []string{} |
| 60 | for _ in 0 .. h { |
| 61 | is_live := rand.f64() > 0.82 |
| 62 | icon := transformers[int(is_live)] |
| 63 | grid[x] << icon |
| 64 | } |
| 65 | } |
| 66 | return Game{grid} |
| 67 | } |
| 68 | |
| 69 | fn main() { |
| 70 | mut g := new_game() |
| 71 | |
| 72 | g.display() |
| 73 | for { |
| 74 | g.evolve() |
| 75 | term.erase_clear() |
| 76 | g.display() |
| 77 | time.sleep(100 * time.millisecond) |
| 78 | } |
| 79 | } |
| 80 | |