Created
January 25, 2011 22:39
-
-
Save jonasb/795852 to your computer and use it in GitHub Desktop.
Conway's Game of Life
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 gameoflife | |
object GameOfLife { | |
def run() { | |
var g = new Generation(50, 50) | |
// Blinker | |
g.set(1, 1, true) | |
g.set(2, 1, true) | |
g.set(3, 1, true) | |
// Glider | |
g.set(6, 3, true) | |
g.set(7, 3, true) | |
g.set(8, 3, true) | |
g.set(8, 2, true) | |
g.set(6, 1, true) | |
println(g) | |
println | |
(0 until 10).foreach {i => g = g.evolve; println(g); println} | |
} | |
def main(args: Array[String]) { | |
run() | |
} | |
} |
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 gameoflife | |
class Generation(width: Int, height: Int) { | |
private val cells = new Array[Boolean](width * height) | |
private def index(x: Int, y: Int) = x + width * y | |
def set(x: Int, y: Int, state: Boolean) = | |
cells(index(x, y)) = state | |
def get(x: Int, y: Int) = | |
cells(index(x, y)) | |
private def neighbours(x: Int, y: Int) = | |
for (a <- (x-1) until (x+1) inclusive; | |
b <- (y-1) until (y+1) inclusive; | |
if !(a==x && b==y) && a>=0 && a<width && b>=0 && b<height) | |
yield cells(index(a, b)) | |
private def livingNeighbours(x: Int, y: Int) = | |
(neighbours (x, y) foldLeft 0) { (c, b) => if (b) (c+1) else c } | |
override def toString = { | |
val sb = new StringBuilder(cells.length) | |
cells.foreach(c => sb.append(if (c) 'X' else '-')) | |
sb.toString.grouped(width).mkString("\n") | |
} | |
def evolve() = { | |
val g = new Generation(width, height) | |
(0 until width).foreach { x => | |
(0 until height).foreach{ y => | |
g.set(x, y, evolveCell(x, y)) | |
} | |
} | |
g | |
} | |
private def evolveCell(x: Int, y: Int) = { | |
val neighbours = livingNeighbours(x, y) | |
val lives = get(x, y) | |
(lives && (neighbours == 2 || neighbours == 3) | |
|| (!lives && neighbours == 3)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment