Skip to content

Instantly share code, notes, and snippets.

@aseigneurin
Created October 8, 2015 09:53
Show Gist options
  • Select an option

  • Save aseigneurin/43c6d35706369114afc0 to your computer and use it in GitHub Desktop.

Select an option

Save aseigneurin/43c6d35706369114afc0 to your computer and use it in GitHub Desktop.
Conway's game of life in Scala
object Conway extends App {
var grid = Grid(3, 3)
while (true) {
grid.print
grid = grid.nextGrid
Thread.sleep(2000)
}
}
case class Cell(active: Boolean) {
override def toString() = if (active) "o" else "."
}
class Grid(width: Int, height: Int, cells: Seq[Seq[Cell]]) {
def print = {
val sep = "----" * width + "-\n"
val str = cells.map(row => row.mkString("| ", " | ", " |\n"))
.mkString(sep, sep, sep)
println(str)
}
def nextGrid: Grid = {
val newCells = (0 to height - 1).map(i => (0 to width - 1).map(j => Cell(newState(i, j))))
new Grid(width, height, newCells)
}
def newState(i: Int, j: Int): Boolean = {
val activeCount = (i - 1 to i + 1).flatMap(x => (j - 1 to j + 1).map(y => (x, y)))
.filter { case (x, y) => !(x == i && y == j) }
.filter { case (x, _) => x >= 0 && x < width }
.filter { case (_, y) => y >= 0 && y < height }
.count { case (x, y) => cells(x)(y).active }
activeCount == 3 || (activeCount == 2 && cells(i)(j).active)
}
}
object Grid {
def apply(width: Int, height: Int): Grid = {
val cells = (0 to height - 1).map(i => (0 to width - 1).map(j => Cell(i == 1)))
new Grid(width, height, cells)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment