#* Conway's Game of Life
  The universe is toroidal (the edges wrap).
*#

include :terminal
width = terminal.width
height = terminal.height - 1

universe = height.of({width.of({random(0,1)})})
next = height.of({width.of(0)})


cell = { x, y |
  x = x % width
  y = y % height
  universe[y][x]
}

neighbors = { x, y |
  cell(x - 1, y - 1) +
  cell(x, y - 1) +
  cell(x + 1, y - 1) +
  cell(x + 1, y) +
  cell(x + 1, y + 1) +
  cell(x, y + 1) +
  cell(x - 1, y + 1) +
  cell(x - 1, y)
}

set_next = { x, y, v |
  next[y][x] = v
}

step = {
  universe.each_with_index { row, y |
    row.each_with_index { c, x |
      n = neighbors(x, y)

      when { n < 2 } { set_next x,y, 0 }
           { n > 3 } { set_next x, y, 0 }
           { n == 3 } { set_next x, y, 1 }
           { true } { set_next x, y, c }
    }
  }

  u2 = universe
  universe = next
  next = u2
}

display = {
  p universe.map({ r |
    r.map({ n | true? n == 0, ' ', "O" }).join
  }).join("\n")
}

loop {
  display
  terminal.to 0, 0
  step
}