Created
November 18, 2011 15:01
-
-
Save mariussoutier/1376684 to your computer and use it in GitHub Desktop.
Game of Life in Scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package keeponlyalive | |
/** A cell that exists is alive */ | |
case class Cell(x: Int, y: Int) { | |
def survives(implicit world: Set[Cell]) = neighborCount(world) match { | |
case 2 => true | |
case 3 => true | |
case _ => false | |
} | |
def resurrects(implicit world: Set[Cell]) = neighborCount(world) == 3 | |
val deltas = (1,0) :: (0,1) :: (1,1) :: (-1,0) :: (0,-1) :: (-1,-1) :: (1, -1) :: (-1, 1) :: Nil | |
// Must be lazy or def, otherwise you'll end up with an endless loop | |
lazy val potentialNeighbors = deltas map { delta => Cell(x + delta._1, y + delta._2) } | |
def neighborCount(implicit world: Set[Cell]) = potentialNeighbors.filter{world.contains(_)}.size | |
} | |
class World(var cells: Set[Cell]) { | |
def nextGeneration { | |
implicit val currentGeneration = cells | |
cells = currentGeneration.filter(_.survives) union resurrectableNeighbours.filter(_.resurrects) | |
} | |
def resurrectableNeighbours(implicit world: Set[Cell]) = world.flatMap(_.potentialNeighbors) | |
override def toString = cells.toList sortWith((cellA,cellB) => cellA.x < cellB.x || cellA.y < cellB.y) mkString(", ") | |
} | |
object GameOfLife extends App { | |
val world = new World(Set(Cell(1,0),Cell(1,1),Cell(1,2))) | |
world.nextGeneration | |
println(world) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment