Tin

Examples · 14 of 339

14-life

Conway's Game of Life on a small torus.

examples/14-life.tintin run examples/14-life.tin
// Conway's Game of Life on a small torus.

let W = 20
let H = 8

fn alive(grid: bool[], x: int, y: int): int {
  let wx = (x + W) % W
  let wy = (y + H) % H
  if grid[wy * W + wx] { 1 } else { 0 }
}

fn step(grid: bool[]): bool[] {
  var next: bool[] = []
  for y in 0..H {
    for x in 0..W {
      var n = 0
      for dy in 0..3 {
        for dx in 0..3 {
          if dx != 1 || dy != 1 { n += alive(grid, x + dx - 1, y + dy - 1) }
        }
      }
      let here = grid[y * W + x]
      next.push(n == 3 || (here && n == 2))
    }
  }
  next
}

fn show(grid: bool[]) {
  for y in 0..H {
    var line = ""
    for x in 0..W {
      line = line + if grid[y * W + x] { "#" } else { "." }
    }
    print(line)
  }
}

fn main() {
  var grid: bool[] = []
  for i in 0..W * H { grid.push(false) }
  // a glider
  for cell in [1, W + 2, 2 * W, 2 * W + 1, 2 * W + 2] { grid[cell] = true }

  show(grid)
  for generation in 0..8 { grid = step(grid) }
  print("after 8 generations:")
  show(grid)
  print("{grid.count(c => c)} cells alive")
}
.#..................
..#.................
###.................
....................
....................
....................
....................
....................
after 8 generations:
....................
....................
...#................
....#...............
..###...............
....................
....................
....................
5 cells alive